资源字典可以把应用程序中一些全局的样式集中放置到一个文件中,方便全局配置
1.创建资源字典文件
DictRes.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="solidbrush" Color="Red"></SolidColorBrush>
<Style TargetType="Button" x:Key="btnstyle">
<Setter Property="Foreground" Value="Red"></Setter>
</Style>
</ResourceDictionary>
2.加入到全局配置
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="WinRes.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DictRes.xaml">
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
使用
<StackPanel Orientation="Vertical">
<Button Content="按钮1" Width="100" Height="50" Background="PaleVioletRed" Margin="10" Click="Button_Click"></Button>
<Button Content="按钮2" Width="100" Height="50" Background="PaleVioletRed" Margin="10" BorderThickness="5" BorderBrush="{StaticResource solidbrush}"></Button>
<Button Content="按钮3" Width="100" Height="50" Background="PaleVioletRed" Margin="10" Style="{StaticResource btnstyle}"></Button>
</StackPanel>
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Resources["solidbrush"] = new SolidColorBrush(Colors.Blue);
var solicColor=App.Current.FindResource("solidbrush");
Console.WriteLine("1");
}