WPF中的“资源”

WPF中的“资源”

资源概述

WPF中的资源的概念有点类似 web 技术中的静态资源的概念。可以是一个样式,也可以是一个button的边框设置集合。
可以简单的将资源分为如下几个类别:

  • 窗体资源:顾名思义,仅可在当前窗体中使用
  • 全局资源:相对于窗体资源而言,是一个全局级别的,可以被多个窗体引用,可以根据不同的维度定义多个全局资源文件
  • 动态资源:“值”可以被改变的资源,例如:程序启动的时候button的边框是红色的,当点击某个其他按钮后,将边框变成蓝色

窗体资源

创建

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

引用

使用花括号和关键字 StaticResource

 <StackPanel>
        <Button Content="我是一个按钮" Margin="10"  BorderBrush="{StaticResource  SolidColor}"></Button>
 </StackPanel>

全局资源

创建 资源字典 文件

右键工程,点击添加-资源字典,命名为  DictionaryButton.xaml

编写全局资源

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="GlobalSolidColor" Color="Yellow"></SolidColorBrush>
    <Style x:Key="DefaultButtonStyle" TargetType="Button">
        <Setter   Property="Foreground"  Value="Blue"  ></Setter>
        <Setter   Property="FontSize"  Value="20"  ></Setter>
        <Setter  Property="BorderBrush" Value="Pink" ></Setter>
        <Setter   Property="BorderThickness"  Value="10"  ></Setter>
    </Style>
</ResourceDictionary>

引入

在 App.xaml 文件中引入全局资源文件 DictionaryButton.xaml

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="DictionaryButton.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

引用

   <StackPanel>
        <Button Content="我是一个按钮" Margin="10"   Style="{StaticResource DefaultButtonStyle}"></Button>
   </StackPanel>

动态资源

就资源本身而言,动态资源并没有什么特殊之处,仅仅是在处理方式上面的差异。

创建

参考 窗体资源

引用

                <StackPanel>
                    <Button Content="改变下面控件的边框颜色" Margin="10"  Click="Button_Click" ></Button>
                    <Button Content="我是一个按钮" Margin="10"  BorderBrush="{DynamicResource  SolidColor}" BorderThickness="10"></Button>
                </StackPanel>

动态编辑资源

   private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Resources["SolidColor"] = new SolidColorBrush(Colors.Blue);
        }

代码

https://github.com/Naylor55/WPF-Taste/tree/main/resource/ResourceTaste

posted @ 2022-12-12 17:21  Naylor  阅读(447)  评论(0编辑  收藏  举报