1. wpf对象级资源
<Window.Resources>
<ResourceDictionary>
<sys:String x:Key="str">
沉舟侧畔千帆过,并书签豆腐.
</sys:String>
<sys:Double x:Key="dbl">
3.1415926
</sys:Double>
<TextBlock x:Key="res1" Text="海上升明月"/>
<TextBlock x:Key="res2" Text="海上生明月"/>
</ResourceDictionary>
</Window.Resources>
2. wpf 资源使用 动态方式与静态方式
资源使用分为静态方式与动态方式
静态方式: 在程序载入内存时,对资源的一次性使用,之后不再访问资源
动态方式: 程序在访问中,仍然会访问资源。
下面例子演示,分别动静两种方式使用资源。当改变资源值时,静态方式下不会更新,动态方式下会更新。
前台代码
<Button Margin="5,5,5,0" Content="{StaticResource ResourceKey=res1}"/>
<Button Margin="5,5,5,0" Content="{DynamicResource ResourceKey=res2}"/>
<Button Margin="5,5,5,0" Content="Update" Click="Button_Click"/>
后台代码
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Resources["res1"] = new TextBlock() { Text = "天涯共此时" };
this.Resources["res2"] = new TextBlock() { Text = "天涯共此时" };
}
3. wpf 资源(二进制资源)
-
如果二进制资源是string 类型,可以使用应用程序Properties名称空间中的Resources.resx资源文件。使用时,
internal改为Public,BuildAction=Embedded Resource -
访问图片资源
例如,把图片文件放在项目下 Img文件夹中
后台代码调用方式
///加载二进制资源 代码中调用资源
Uri imguri = new Uri(@"Img/1.jpg", UriKind.Relative);
this.Image3.Source= new BitmapImage(imguri);
///代码中调用资源
Uri uri = new Uri(@"pack://application:,,,/Img/1.jpg", UriKind.Absolute);
this.Image4.Source = new BitmapImage(uri);
示例代码下载地址
点击下载