我有一个项目,我想在其中显示不同类型的项目的集合 - 在我的最初情况下bool
、string
和 StringList
实际上只是一个ObservableCollection<string>
。
我想做的是将每个项目呈现为可以编辑该项的适当控件 - 例如,复选框、文本框、DataGrid。
我可以通过添加由数据类型键控的 DataTemplate 资源来完成所有这些工作。 但是,这里的问题变成了能够有选择地重用这些模板,而无需在整个项目范围内应用它们。 毕竟,我当然不希望string
的每一条内容都成为文本框! 现在,我通过将资源仅添加到单个控件的资源集合来限制范围,这效果很好,除非我想创建这样的第二个控件时,我会复制和粘贴大量模板代码,这似乎是错误的。
允许选择性重用的最佳方法是什么? 这是我目前拥有的示例:
<ContentControl Grid.Column="1" Content="{Binding Value}" Padding="0,10,0,0" >
<ContentControl.Resources>
<DataTemplate DataType="{x:Type sys:Boolean}">
<CheckBox Width="64" IsChecked="{Binding Path=.}" />
</DataTemplate>
<DataTemplate DataType="{x:Type sys:String}">
<TextBox Width="100" Text="{Binding Path=.}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:StringList}">
<DataGrid ItemsSource="{Binding Path=.}" AutoGenerateColumns="False" HeadersVisibility="None" CanUserAddRows="True" Width="100" Height="50">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=.}" Width="*" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
在ResourceDictionary
中定义DataTemplates
,并将此ResourceDictionary
添加到要应用模板的每个ContentControl
:
<ContentControl Grid.Column="1" Content="{Binding Value}" Padding="0,10,0,0" >
<ContentControl.Resources>
<ResourceDictionary Source="Dictionary1.xaml" />
</ContentControl.Resources>
</ContentControl>
词典1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate DataType="{x:Type sys:Boolean}">
<CheckBox Width="64" IsChecked="{Binding Path=.}" />
</DataTemplate>
<DataTemplate DataType="{x:Type sys:String}">
<TextBox Width="100" Text="{Binding Path=.}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:StringList}">
<DataGrid ItemsSource="{Binding Path=.}" AutoGenerateColumns="False" HeadersVisibility="None" CanUserAddRows="True" Width="100" Height="50">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=.}" Width="*" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</ResourceDictionary>
您可以将要有选择地重用的数据模板资源定义为单独的文件 ResourceDictionary,然后使用合并的字典在用户控件中使用它们。
看看这里 https://blogs.msdn.microsoft.com/wpfsldesigner/2010/06/03/creating-and-consuming-resource-dictionaries-in-wpf-and-silverlight/
我希望它有所帮助。