【发布时间】:2014-04-10 08:15:43
【问题描述】:
从 ResourceDictionary 中定义的 DataTemplate 中引用 StaticResources 时,我遇到了一些奇怪的行为。
在此示例中,我使用 ResourceDictionary 中定义的 DataTemplate 填充数字 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>
StaticResource CoolNumbersColor 与 ResourceDictionary1.xaml 一起在 App.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 设计器中看到预期的行为。确实出现了一个彩色数字列表。但是在尝试运行此示例时,我收到错误
"找不到名为 'CoolNumbersColor' 的资源。资源名称为 区分大小写”
我不明白为什么会这样。 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>
【问题讨论】:
-
你在哪里使用这个资源?我在小应用程序中尝试过,最终效果很好。
-
您是否尝试在 Application.Resources 中的 ResourceDictionary.MergedDictionaries 之前定义 CoolNumbersColor ?
-
是的,我在
DataTemplate的ListBox中使用了它。仍然没有问题。你可以在小应用程序中尝试吗?我怀疑问题出在其他地方。 -
在单独的 ResourceDictionary 上定义 DataTemplate。这种方式对我不起作用。
标签: wpf xaml datatemplate staticresource