当在 ResourceDictionary 中定义的 DataTemplate 中引用 StaticResources 时,我遇到了一些奇怪的行为。
在此示例中,我使用在 ResourceDictionary 中定义的 DataTemplate,向 ListBox 填充数字 1 到 9。
以下是 MainWindow.xaml 代码:
<Window x:Class="testResources.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="525"
Height="350">
<Grid>
<ListBox Width="100" ItemTemplate="{StaticResource NumberTemplate}">
<ListBox.ItemsSource>
<Int32Collection>1,2,3,4,5,6,7,8,9</Int32Collection>
</ListBox.ItemsSource>
</ListBox>
</Grid>
NumberTemplate
是在 ResourceDictionary1.xaml 中定义的:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate x:Key="NumberTemplate">
<Grid Background="{StaticResource CoolNumbersColor}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="35" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Background="{StaticResource CoolNumbersColor}" Text="{Binding Mode=OneWay}" />
</Grid>
</DataTemplate>
静态资源CoolNumbersColor
在App.xaml中定义,与ResourceDictionary1.xaml
一起。这是我的App.xaml文件:
<Application x:Class="testResources.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<SolidColorBrush x:Key="CoolNumbersColor">GreenYellow</SolidColorBrush>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/ResourceDictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
首先,我可以在Visual Studio 2010设计器中看到期望的行为。确实会显示一个有颜色的数字列表。但是当尝试运行这个示例时,我收到了以下错误:
"Cannot find resource named 'CoolNumbersColor'. Resource names are case sensitive"
我不明白为什么会发生这种情况。难道CoolNumbersColor
的评估方式有些延迟吗?从词法上讲,它在合并的资源字典前面。
除了使用DynamicResources之外,使其工作的唯一方法是创建第二个ResourceDictionary(例如ResourceDictionary2.xaml),在那里定义CoolNumbersColor
,并将它们全部合并在ResourceDictionary.MergedDictionaries
中,如下所示:
<Application x:Class="testResources.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/ResourceDictionary2.xaml" />
<ResourceDictionary Source="pack://application:,,,/ResourceDictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>