使用AutoGenerateColumns的WPF Datagrid中的ItemTemplateSelector [英] ItemTemplateSelector in WPF Datagrid with AutoGenerateColumns
问题描述
在我们的数据网格中,我们使用 ItemTemplateSelector
根据绑定到特定单元格的数据在两个数据模板之间切换。
由于列数取决于当前的数据集,我们在 DataGrid $ c $中使用
AutoGenerateColumns
c>。
看起来这个特殊组合不能正常工作 -
模板选择器甚至不被调用。
我们可以在自动创建列的数据网格中使用模板选择器吗?
:是否可以使用仅限XAML 将逻辑放入代码隐藏文件或使用自定义行为?
我们的数据网格定义相当简单:
< DataGrid
ItemTemplateSelector ={StaticResource myCustomDataTemplateSelector}
ItemsSource ={Binding MyData}>
< DataGrid.Columns>
< /DataGrid.Columns>
< / DataGrid>
项目模板选择器定义:
< UserControl.Resources>
< ResourceDictionary>
< helpers:CustomDataTemplateSelector x:Key =myCustomDataTemplateSelector/>
< / ResourceDictionary>
< /UserControl.Resources>
首先,
ItemTemplate和ItemTemplateSelector是继承的属性,
在DataGrid中被故意忽略,因为它们并不真正适用于
DataGrid,它们的意思是到$ Items $。
$ p
如果你的意思是要根据其价值来修改单元格模板,那么你是在DataGridTemplateColumn
上查找CellTemplateSelector
。但是,当您自动生成列时,它已经自动选择底层类型。
您可以覆盖在
GeneratingColumns
事件中的行为。
参见:在WPF中使用CellTemplateSelector的DataTemplateCell DataGrid自动生成的列
如果需要更多的控制,您可能需要查看 https://zamjad.wordpress.com/2011/09/17/ datagrid-with-dynamic-columns-revisited /
In our data grid we're using an
ItemTemplateSelector
to switch between two data templates based on the data bound to a particular cell.As the number of columns depends on the current data set we're using
AutoGenerateColumns
in ourDataGrid
.It appears that this particular combination does not work well -
the template selector isn't even called.Can we use the template selector in a data grid where columns are created automatically?
More specifically: Is this possible using XAML only w/o putting logic into the code-behind file or using custom behaviours?
Our data grid definition is fairly trivial:
<DataGrid ItemTemplateSelector="{StaticResource myCustomDataTemplateSelector}" ItemsSource="{Binding MyData}"> <DataGrid.Columns> </DataGrid.Columns> </DataGrid>
The item template selector definition:
<UserControl.Resources> <ResourceDictionary> <helpers:CustomDataTemplateSelector x:Key="myCustomDataTemplateSelector"/> </ResourceDictionary> </UserControl.Resources>
解决方案First,
ItemTemplate and ItemTemplateSelector are inherited properties which are purposely ignored in the DataGrid since they don't really apply to DataGrid in the way that they were meant to in ItemsControl.
Secondly, if you mean that you want to modify cell templae based on its value, you are looking for
CellTemplateSelector
, on aDataGridTemplateColumn
.However, when you auto-generate columns, it already chooses the underlying types automatically.
You can override that behavior in
GeneratingColumns
event.See this: Force DataTemplateCell with CellTemplateSelector in WPF DataGrid Autogenerated columns
If you need more control, you might want to take a look at https://zamjad.wordpress.com/2011/09/17/datagrid-with-dynamic-columns-revisited/
这篇关于使用AutoGenerateColumns的WPF Datagrid中的ItemTemplateSelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!