【发布时间】:2011-08-02 14:21:12
【问题描述】:
我有两个定义为静态资源的数据模板。现在我有一个包含每个名称的组合框。是否可以让您的控件利用这些静态资源作为项目模板来绑定到组合框中所选静态资源的名称?
提前致谢。
【问题讨论】:
我有两个定义为静态资源的数据模板。现在我有一个包含每个名称的组合框。是否可以让您的控件利用这些静态资源作为项目模板来绑定到组合框中所选静态资源的名称?
提前致谢。
【问题讨论】:
这里有一些看起来很疯狂但运行良好的东西。
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ComboBox x:Name="cboTemplate" DisplayMemberPath="Key" SelectedValuePath="Key" SelectedValue="Blue">
<ComboBox.ItemsSource>
<ResourceDictionary>
<DataTemplate x:Key="Blue">
<TextBlock Foreground="Blue" Text="{Binding}" />
</DataTemplate>
<DataTemplate x:Key="Red">
<TextBlock Foreground="Red" Text="{Binding}" />
</DataTemplate>
</ResourceDictionary>
</ComboBox.ItemsSource>
</ComboBox>
<ContentPresenter Grid.Row="1" Content="Hello World" ContentTemplate="{Binding SelectedItem.Value, ElementName=cboTemplate}" />
</Grid>
资源字典基本上是KeyValuePair<object, object> 的集合,但Xaml 解析提供了使用x:Key 属性填充它的优势。所以这个 ComboBox 显示了Key 属性,但它的SelectedItem 将是KeyValuePair<object, object>,其Value 属性是我们想要的DataTemplate。我们现在可以在 ContentTemplate 或 ItemTemplate 属性上使用元素到元素的绑定。
如果您还需要可用作静态资源的 DataTemplate,并且希望避免代码重复,您可以将它们放在单独的资源字典 xaml 文件中。然后你可以使用:-
<ComboBox.ItemsSource>
<ResourceDictionary Source="DataTemplateResources.xaml" />
</ComboBox.ItemsSource>
以及将它们包含在静态资源中,例如:-
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DataTemplateResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- other resources here -->
</ResourceDictionary>
</UserControl.Resources>
【讨论】: