10.2 且“静”且“动”用资源
静态资源使用(StaticResource)指的是在程序载入内存时对资源的一次性使用,之后就不再去访问这个资源了;动态资源使用(DynamicResource)指的是在程序运行过程中仍然会去访问资源。显然,如果你确定某些资源只在程序初始化的时候使用一次、之后不会改变,就应该使用StaticResource,而程序运行过程中还有可能改变的资源应该以DynamicResource形式使用。
<Window.Resources>
<ResourceDictionary>
<sys:String x:Key="str">大话西游</sys:String>
</ResourceDictionary>
</Window.Resources>
<StackPanel Orientation="Vertical">
<TextBlock Text="{DynamicResource ResourceKey=str}" Margin="5"/>
<Button Content="OK" Width="80" Click="Button_Click"/>
</StackPanel> private void Button_Click(object sender, RoutedEventArgs e)
{
this.Resources["str"] = "月光宝盒";
}10.3 向程序添加二进制资源
我们明确地称呼资源词典里的资源为“WPF资源”或对象资源,称呼应用程序的内嵌资源为“程序集资源”或二进制资源。WPF程序中写在<Application.Resources>..</ApplicationResources>标签内的资源仍然是WPF资源而非二进制资源。
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="5"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<Image x:Name="img1" Grid.Row="0"/>
<TextBlock Text="{x:Static Member=local:Resources.String1}" Grid.Row="2" HorizontalAlignment="Center"/>
</Grid> var testImg = FirstWpfApplication.Resources.Image1;
MemoryStream st = new MemoryStream();
testImg.Save(st, System.Drawing.Imaging.ImageFormat.Png);
ImageSourceConverter converter = new ImageSourceConverter();
this.img1.Source = (ImageSource)converter.ConvertFrom(st);如果想让外部文件编译进目标成为二进制资源,必须在属性窗口中把文件的Build Action属性设为Resource。
10.4 使用Pack URI路径访问二进制资源
<Image x:Name="img1" Grid.Row="0" Source="/images/Image1.jpg"/>[文件夹名称/]文件名称
1641

被折叠的 条评论
为什么被折叠?



