在.cs文件中創(chuàng)建ControlTemplate

之前的工作中遇到需要設(shè)置圓角button的問(wèn)題,雖然可以在xaml中設(shè)置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在控件大小自適應(yīng)屏幕的時(shí)候,就不能保持相同的弧度了。此時(shí)需要?jiǎng)討B(tài)的創(chuàng)建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;
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

  • 1 CALayer IOS SDK詳解之CALayer(一) http://doc.okbase.net/Hell...
    Kevin_Junbaozi閱讀 5,337評(píng)論 3 23
  • 表情是什么,我認(rèn)為表情就是表現(xiàn)出來(lái)的情緒。表情可以傳達(dá)很多信息。高興了當(dāng)然就笑了,難過(guò)就哭了。兩者是相互影響密不可...
    Persistenc_6aea閱讀 129,647評(píng)論 2 7
  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險(xiǎn)厭惡者,不喜歡去冒險(xiǎn),但是人生放棄了冒險(xiǎn),也就放棄了無(wú)數(shù)的可能。 ...
    yichen大刀閱讀 7,820評(píng)論 0 4

友情鏈接更多精彩內(nèi)容