1.在App.xaml文件中定义,
<!--按钮样式-->
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Background" Value="Silver"/>
<Setter Property="Height" Value="23"/>
</Style>
<!--TextBox样式,这样写可以应用自动所有TextBox-->
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBoxBase}">
<Setter Property="Foreground" Value="Red"/>
</Style>
这是两种不同的设置方式,对于ButtonStyle需要手工指定需要绑定此样式的Control,可以参见下面的绑定代码;但是对于TextBox这个样式可以应用于整个项目的所有TextBox控件。
手工绑定样式代码:
<Button Margin="54,0,0,14" Name="button1" VerticalAlignment="Bottom" Style="{StaticResource ButtonStyle}" Click="button1_Click" IsDefault="True" Height="23" HorizontalAlignment="Left" Width="51">登陆(_L)</Button>
或者
button2.Style = (Style)this.TryFindResource("ButtonStyle");
2.合并资源字典
<Application.Resources>
<!-- Resources scoped at the Application level should be defined here. -->
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles\Button.xaml"/>
<ResourceDictionary Source="Styles\ComboBox.xaml"/>
<ResourceDictionary Source="Styles\Shared.xaml"/>
<ResourceDictionary Source="Styles\TextBox.xaml"/>
<ResourceDictionary Source="Styles\ListView.xaml"/>
<ResourceDictionary Source="Styles\GroupBox.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
然后就是创建资源字典了,Add Items有”资源字典”这个模板。