WPF资源

发布时间 2023-11-30 14:30:28作者: 无处不在-超超

一、静态动态资源

1.资源定义

    <Window.Resources>
        <SolidColorBrush x:Key="SolidColor" Color="Red"/>
    </Window.Resources>

 

2.资源使用:动态、静态

            <Button Content="button1" BorderBrush="{StaticResource SolidColor}" Margin="10"/>
            <Button Content="button1" BorderBrush="{DynamicResource SolidColor}" Margin="10"/>

3.动态资源修改值

this.Resources["SolidColor"] = new SolidColorBrush(Colors.Black);

二.将资源放入到资源字典中

1.创建资源字典(.xaml)

2.定义相关资源

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="SolidColor" Color="Red" />
    <Style x:Key="DefaultButtonStyle" TargetType="Button">
        <Setter Property="Foreground" Value="Blue" />
        <Setter Property="FontSize" Value="15" />
    </Style>

</ResourceDictionary>

3.将资源字典加入到全局资源中

<Application
    x:Class="WpfApp2.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp2"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ButtonStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

三、资源查找

var solidColor = App.Current.FindResource("SolidColor");