WPF学习笔记7. Resource
2010-10-11 16:19:14 来源:本站整理核心提示:当然,静态资源也有另外一个麻烦,WPF学习笔记7. Resource(4),就是不支持前向引用(Forward Reference),也就是说我们必须先定义资源,那么 Dictionary2.label1 将获胜,在程序代码中我们可以用 FindResource/TryFindResource 设置静态资源,然后才能使
当然,静态资源也有另外一个麻烦,就是不支持前向引用(Forward Reference),也就是说我们必须先定义资源,然后才能使用静态引用。
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Grid>
<StackPanel>
<Label Content="{StaticResource label}" />
</StackPanel>
</Grid>
<Window.Resources>
<ContentControl x:Key="label">Hello, World!</ContentControl>
</Window.Resources>
</Window>
属于静态资源的异常出现了,当然动态资源是没有这个问题的。

如果有必要的话,我们可以将逻辑资源分散定义在多个 XAML 文件(Resource Dictionary) 中。

Dictionary1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ContentControl x:Key="label1">Hello, World!</ContentControl> </ResourceDictionary>
Dictionary2.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ContentControl x:Key="label2">Hello, C#!</ContentControl> </ResourceDictionary>
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml" />
<ResourceDictionary Source="Dictionary2.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<StackPanel>
<Label Content="{DynamicResource label1}" />
<Label Content="{DynamicResource label2}" />
</StackPanel>
</Grid>
</Window>
如果合并的字典中有重复的键值,那么最后加入的资源将优先。比如 Dictionary1.xaml 和 Dictionary2.xaml 都有一个 x:Key="label1" 的资源,那么 Dictionary2.label1 将获胜。
在程序代码中我们可以用 FindResource/TryFindResource 设置静态资源,用 SetResourceReference 设置动态资源。
this.labelA.Content = (ContentControl)this.labelA.FindResource("key1"); // StaticResource
this.labelB.SetResourceReference(Label.ContentProperty, "key2"); // DynamicResource
[]
更多精彩
赞助商链接