WPF静态资源动态资源资源字典的详解
MainWindow前端代码
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<Button Content="Update" Height="40" Click="Button_Click" Margin="10"/>
<!--StaticResource 静态资源 不会发生变化-->
<Button Content="Button1" Height="40" BorderBrush="{StaticResource QCSolidColor}" BorderThickness="5" Margin="10"/>
<!--DynamicResource 动态资源 可以发生变化-->
<Button Content="Button2" Height="40" BorderBrush="{DynamicResource QCSolidColor}" BorderThickness="5" Margin="10"/>
</StackPanel>
</Grid>
</Window>
MainWindow后端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Resources["QCSolidColor"]=new SolidColorBrush(Colors.Black); //更改QCSolidColor的Color为黑色
var SolidStyle1 = App.Current.FindResource("QCSolidColor"); //搜索资源 FindResource
var ButtonStyle1 = App.Current.FindResource("DefaultButton");
}
}
}
资源字典的使用 有的时候定义的样式太多 需要单独新建一个资源字典来放置Style
ButtonStyle.xaml
ButtonStyle.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="DefaultButton" TargetType="Button">
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="FontSize" Value="15"/>
</Style>
</ResourceDictionary>
SolidStyle
SolidStyle.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="QCSolidColor" Color="Red"/>
</ResourceDictionary>
最后在App.xaml中引用
代码如下
<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="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="SolidStyle.xaml"/>
<ResourceDictionary Source="ButtonStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>