WPF之资源

WPF中的数据分为四个等级存储:数据库、资源文件、WPF对象、变量

 

每个WPF的界面元素都有一个名为Resources的属性,这个属性继承自FrameworkElement类,起类型为ResourceDictionary,ResourceDictionary能够以“key-value”对的形式存储资源,在保存资源时,ResourceDictionary认为资源对象的类型是object。

 

[html] view plain copy
 
  1. <Window x:Class="WpfApplication17.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:sys="clr-namespace:System;assembly=mscorlib"  
  5.         Title="MainWindow" Height="350" Width="525">  
  6.     <Window.Resources>  
  7.         <ResourceDictionary>  
  8.             <sys:String x:Key="str">WPF对象资源</sys:String>  
  9.         </ResourceDictionary>  
  10.     </Window.Resources>  
  11.     <StackPanel>  
  12.         <Button Content="{StaticResource ResourceKey=str}" />  
  13.     </StackPanel>  
  14. </Window>  

在检索资源时,先查找控件自己的Resources属性,如果没有找到,会沿着逻辑树向上查找,最后到达Application.Resources,如果还是找不到,就会报异常了

 

在C#代码中也可以使用定义在XAML代码里的资源

 

[csharp] view plain copy
 
  1. button1.Content = FindResource("str");  

 

 

[csharp] view plain copy
 
  1. button1.Content = Resources["str"];  

ResourceDictionary可以包含另一个xaml文件,这样就可以先把皮肤做好,需要使用的时候包含就可以了

 

加载资源词典中的资源,可以使用静态和动态两种方式使用这些资源:StaticResource和DynamicResource

 

[html] view plain copy
 
  1. <Button Content="{StaticResource ResourceKey=str}" />  
  2. <Button Content="{DynamicResource ResourceKey=str}" />  

两种用法的区别是,动态资源只会加载一次,以后资源变化后,界面也不会变化,动态资源是实时更新的,当资源在运行时发生变化后,界面也会变化

 

也可以将资源打包到最终的exe或dll中,如果要添加的资源是文字而非文件,可以使用应用程序properties名称空间中的Resources.resx资源文件,为了让xaml文件能访问这个类,一定要把Resources.resx的访问级别改成Public,然后就可以在xmal中使用了,使用x:Static标签扩展来访问

首先导入Resources的命名空间

 

[html] view plain copy
 
  1. xmlns:prop="clr-namespace:WpfApplication17.Properties"  

然后使用x:Static标签来访问资源

 

 

[html] view plain copy
 
  1. <Button Content="{x:Static prop:Resources.str}" />  

也可以在C#代码中访问资源

 

 

[csharp] view plain copy
 
  1. button1.Content = Properties.Resources.str;  

posted on 2017-07-26 09:24  alex5211314  阅读(278)  评论(0编辑  收藏  举报

导航