美文网首页
在.cs文件中创建ControlTemplate

在.cs文件中创建ControlTemplate

作者: 分享学习 | 来源:发表于2021-07-15 09:50 被阅读0次

    之前的工作中遇到需要设置圆角button的问题,虽然可以在xaml中设置cornerRadius

    <ControlTemplate x:Key="radiusBtnTemplate" TargetType="{x:Type ButtonBase}">
        <Border CornerRadius="5" Background="#FF19ADF0" Margin="20 10" TextBlock.Foreground="White" BorderBrush="#FF1F6BC2">
            <Viewbox>
                <TextBlock Margin="10">
                     <ContentPresenter Content="{TemplateBinding ContentControl.Content}"/>
                </TextBlock>
            </Viewbox>
        </Border>
    </ControlTemplate>
    

    但是,随着屏幕的缩放,固定大小的CornerRadius在控件大小自适应屏幕的时候,就不能保持相同的弧度了。此时需要动态的创建ControlTemplate方法

    public ControlTemplate GetControlTemplate(double cornerRadius,string colorStr, Thickness? margin = null)
            {
                FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
                border.SetValue(Border.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString(colorStr)));
                border.SetValue(Border.CornerRadiusProperty, new CornerRadius(cornerRadius));
                if (null != margin)
                {
                    border.SetValue(Border.MarginProperty, margin);
                }
    
                FrameworkElementFactory vb = new FrameworkElementFactory(typeof(Viewbox));
                border.AppendChild(vb);
    
                FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
                tb.SetValue(TextBlock.MarginProperty, new Thickness(10));
                vb.AppendChild(tb);
    
                FrameworkElementFactory cp = new FrameworkElementFactory(typeof(ContentPresenter));
                cp.SetValue(ContentPresenter.ContentProperty, new TemplateBindingExtension(ContentControl.ContentProperty));
                tb.AppendChild(cp);
    
                ControlTemplate ct = new ControlTemplate();
                ct.VisualTree = border;
                return ct;
            }
    

    相关文章

      网友评论

          本文标题:在.cs文件中创建ControlTemplate

          本文链接:https://www.haomeiwen.com/subject/mcjppltx.html