Wpf基础入门——资源(Resources)

发布时间 2023-05-29 21:06:51作者: Swbna

本篇文章学习于: 刘铁猛老师《深入浅出WPF》

WPF 对象级资源

每个WPF的界面元素都具有一个名为Resources 的属性,这个属性继承自FrameworKElement类,其类型为ResourceDictionary。ResourceDictionary 能够以“键一值”对的形式存储资源,当需要使用某个资源时,使用“键一值”对可以索引到资源对象。在保存资源时,ResourceDictionary视资源对象为object类型,所以在使用资源时先要对资源对象进行类型转换,XAML编译器能够根据标签的Attribute自动识别资源类型,如果类型不对就会抛出异常,但在C#代码里检索到资源对象后,类型转换的事情就只能由我们自己来做了。

<Window x:Class="Demo6.Wpf资源.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:Demo6.Wpf资源"
  xmlns:sys="clr-namespace:System;assembly=mscorlib"
  mc:Ignorable="d"
  Title="MainWindow" Height="450" Width="800">
  <Window.Resources>
    <sys:String x:Key="str">资源学习</sys:String>
    <sys:Double x:Key="Pi">3.1415926</sys:Double>
  </Window.Resources>
  <Grid>
    <TextBlock Text="{StaticResource str}"/>
  </Grid>
</Window>

image.png

检索资源的顺序:
在检索资源时,先查找控件自己的Resources属性,如果没有这个资源程序会沿着逻辑树向上一级控件查找,如果连最顶层容器都没有这个资源,程序就会去查找 Application.Resources(也就是程序的顶级资源),如果还没找到,那就只好抛出异常了。

StaticResource和DynamicResource

当资源被存储进资源词典后,我们可以通过两种方式来使用这些资源—静态方式和动态方式。
静态资源使用(StaticResource)指的是在程序载入内存时对资源的一次性使用,之后就不再去访问这个资源了。
动态资源使用(DynamicResource)使用指的是在程序运行过程中仍然会去访问资源。
显然,如果你确定某些资源只在程序初始化的时候使用一次、之后不会再改变,就应该使用StaticResource,而程序运行过程中还有可能改变的资源应该以DynamicResource形式使用。

示例:

<Window x:Class="Demo6.Wpf资源.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:Demo6.Wpf资源"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <sys:String x:Key="str">资源学习</sys:String>
        <sys:Double x:Key="Pi">3.1415926</sys:Double>
        <TextBlock x:Key="tb1" Text="1111"/>
        <TextBlock x:Key="tb2" Text="1111"/>
    </Window.Resources>
    <StackPanel>
        <TextBlock Text="{StaticResource str}"/>
        <Button Content="{StaticResource tb1}"/>
        <Button Content="{DynamicResource tb2}"/>
        <Button Content="更新" Name="btnUpdate" Click="btnUpdate_Click"/>
    </StackPanel>
</Window>

image.png
image.png

namespace Demo6.Wpf资源 {
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }

        private void btnUpdate_Click(object sender, RoutedEventArgs e) {
            this.Resources["tb1"] = "2222";
            this.Resources["tb2"] = "2222";
        }
    }
}