Wpf Button自定义样式

时光毁灭记忆、已成空白 提交于 2019-12-09 03:59:46

我们制作一个鼠标经过改变背景色的Button。

点解解决方案,为WPF窗体程序添加一个Wpf自定义控件库CustomBtnLibrary。

首先我们定义的一个类我们叫它cButton,用依赖属性注册一个MouseOverBackground.

public class cButton : Button
{  

       public static readonly DependencyProperty MouseOverBackgroundProerty =
            DependencyProperty.Register("MouseOverBackground",typeof(Brush),typeof(cButton),new PropertyMetadata(Brushes.RoyalBlue));




        public Brush MouseOverBackground
        {
            get { return (Brush)GetValue(MouseOverBackgroundProerty); }
            set { SetValue(MouseOverBackgroundProerty, value); }
        }




        static cButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(cButton), new FrameworkPropertyMetadata(typeof(cButton)));
        }

}

打开Themes文件下的Generic.xaml

xmlns:local="clr-namespace:CustomBtnLibrary">添加命名空间

在Border标签下添加 ContenPresenter 为了显示内容,在ControlTemplate下添加 ControlTempleate.Triggers (Triggers事件触发器)

<ControlTemplate TargetType="{x:Type local:cButton}">
                    <Border x:Name="border" 
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            CornerRadius="{Binding RelativeSource={RelativeSource Mode=TemplatedParent },Path=CornerRadius}">
                        <ContentPresenter x:Name="content" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                          Content="{TemplateBinding Content}"/>
               
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},
                                Path=MouseOverBackground }" TargetName="border" /> 
                        </Trigger>
                    </ControlTemplate.Triggers>


在启动窗口MainWindow.xaml添加代码
添加命名空间
xmlns:local="clr-namespace:CustomBtnLibrary;assembly=CustomBtnLibrary"

<Grid>
        <local:cButton Width="100" Height="40" CornerRadius="12" Background="#4000"  PressedBackground="#8000" Content="哈哈"
                       Foreground="White" VerticalContentAlignment="Center"
                       HorizontalContentAlignment="Center"/>
    </Grid>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!