WPF里样式属性的简单使用源码加说明
wpf博大精深,除了数据绑定外,最突出的就是属性和触发器就是,它从html+css里继承了许多优秀的特点,本文就样式里属性展开,我用了5个button做对比,总共有三个文件:一个窗体xaml,一个资源字典Dictionary1.xaml,还有app.xaml需要修改。先看效果:
先上窗体MainWindow.xam的代码:
<Window x:Class="WpfApp5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp5"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" >
资源文件,可以房子啊窗体xaml里,也i可放在专门的资源文件里,但是 需要在app.xaml里说明
<Window.Resources >
<SolidColorBrush x:Key="col" Color="Yellow" ></SolidColorBrush>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
静态属性,属性是不会变的
<Button Background ="{StaticResource col }" Grid.Row="0" Margin=" 10 10 " Width="30" Height="50"></Button>
动态的属性,允许后台修改其属性
<Button Click="btn_ChangeColor" Background ="{DynamicResource col }" Grid.Row="1" Margin=" 10 10 " Width="30" Height="50"></Button>
从资源文件里获取到的属性
<Button Style ="{StaticResource demo1 }" Grid.Row="2" Margin=" 10 10 " Width="30" Height="50"></Button>
<Button Background ="{StaticResource demo2}" Grid.Row="3" Margin=" 10 10 " Width="30" Height="50"></Button>
<Button Style ="{StaticResource demo3 }" Grid.Row="4" Margin=" 10 10 " Width="30" Height="50"></Button>
</Grid>
</Window>
接着呈上资源字典文件 Dictionary1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp5">
<Style x:Key="demo1" TargetType="{x:Type Button}" >复合属性,即有多个setter
<Setter Property="Background" Value="Chocolate" />
<Setter Property="FontSize" Value= "50" />
<Setter Property="Foreground" Value="Blue" />
</Style>
<SolidColorBrush x:Key="demo2" Color="Red" />
<Style x:Key="demo3" TargetType="{x:Type Button}" BasedOn="{StaticResource demo1}"/>属性是可以继承的,但是不能同名
</ResourceDictionary>
要用资源字典,一定要在app.xaml里说明,才会生效
<Application x:Class="WpfApp5.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp5"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!--字典文件的引用-->
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries >
<ResourceDictionary Source="Dictionary1.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>