9.WPF资源

9.WPF资源

9.WPF资源

每个WPF界面元素都有一个Resources属性,类型为ResourceDictionary,在保存资源时,ResourceDictionary将所有的资源视为Object类型,所以需要进行类型转化。

资源的定义与查找

  • 资源放在XAML中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="50" Width="200">
<Window.Resources>
<ResourceDictionary>
<sys:String x:Key="str">
字符串资源
</sys:String>
</ResourceDictionary>
</Window.Resources>
<StackPanel>
<TextBlock Text="{StaticResource ResourceKey=str}" Margin="5"/>
</StackPanel>
</Window>

在检索资源时,会先查找控件自己的Resources属性,如果没有,则沿着逻辑树向上查找,如果最顶层容器也没有该资源,程序则会去查找Application.Resources,程序集资源。如果还没有则抛出异常。

C#使用定义在XAML中的资源this.FindResource("str");如果明确资源放在那个资源字典中,string txt = (string)this.Resources["str"];

  • 资源放在外部文件中
1
2
3
<Window.Resources>
<ResourceDictionary Source="./hello.xaml"/>
</Window.Resources>

动态资源和静态资源

  • 静态资源:在程序载入内存时对资源的一次性加载和使用,之后不再访问
  • 动态资源:程序在运行过程中仍然会去访问该资源
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<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:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="100" Width="200">
<Window.Resources>
<TextBlock x:Key="res1" Text="海上生明月"/>
<TextBlock x:Key="res2" Text="海上生明月"/>
</Window.Resources>
<StackPanel>
<Button Content="{StaticResource res1}"/>
<Button Content="{DynamicResource res2}"/>
<Button Content="更新" Click="Button_Click"/>
</StackPanel>
</Window>
1
2
3
4
5
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Resources["res1"] = new TextBlock() { Text = "天涯共此时" };
this.Resources["res2"] = new TextBlock() { Text = "天涯共此时" };
}

二进制资源

在Properties的Resources.resx中添加string类型

如果要在xaml中使用资源

1
2
3
xmlns:prop="clr-namespace:WpfApp1.Properties"

<TextBlock Text="{x:Static prop:Resources.helllo2}"/>

其他资源直接在解决方案中新建文件夹增加外部资源,如果想让外部资源编程成二进制资源,需要设置文件的生成操作为Resource(不是嵌入的资源)。

使用二进制资源

WPF使用Pack URL来访问二进制资源,Pack URL格式

pack://application,,,[/程序集名称;][可选版本号;][文件夹名称/]文件名称

实际使用时pack://application,,,可以省略,[/程序集名称;][可选版本号;]采用默认值

例如:

<Image x:Name="img" Source="dd/R-C.PNG"/>

作者

步步为营

发布于

2024-05-08

更新于

2025-03-15

许可协议