WPF Button 样式资源设置&后台生成button样式

起这个名字,如果你被题目吸引了内容却不是你想要的,sorry啊.

网上很多讲WPF的样式设置,基本上是在XAML中生成,我遇到的是,自己后台生成button,设定了背景图片,想做到鼠标划过button时(获得焦点同理)有发光的效果,下面记录的内容:

先在项目xaml的resources中加入comtrolTemplate的内容,下面这里包括了鼠标划过及获得焦点事件.

<Window.Resources>
        <ControlTemplate TargetType="Button" x:Key="ButtonTemplate">
            <Border Name="border" CornerRadius="8"  Background="{TemplateBinding Background}">
                <ContentPresenter Name="content" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                              RecognizesAccessKey="True" 
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
            </Border>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Effect">
                        <Setter.Value>
                            <DropShadowEffect BlurRadius="10" Color="Black" Direction="0" Opacity="0.6"
 RenderingBias="Performance" ShadowDepth="0"/>
                        </Setter.Value>
                    </Setter>
                </Trigger>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Effect">
                        <Setter.Value>
                            <DropShadowEffect BlurRadius="10" Color="Black" Direction="0" Opacity="0.6"
 RenderingBias="Performance" ShadowDepth="0"/>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Window.Resources>

第二步,在cs中生成的button,这里的"ButtonTemplate"跟第一步的x:Key="ButtonTemplate"同名

 Button tbi = new Button()
                    {
                        Width =200,
                        Height=100,
                        Template = this.Resources["ButtonTemplate"] as ControlTemplate
                    };

WPF获得焦点后如何让边框发光http://blog.kiccp.com/200.html

原来学习来源WPF中的ControlTemplate(控件模板):http://www.cnblogs.com/zhouyinhui/archive/2007/03/28/690993.html

原文地址:https://www.cnblogs.com/bkycjj/p/3334965.html