在阅读关于如何Customize Auto-Generated Columns的优秀文章后,我遇到了一个问题。自定义DataGrid控件中的自动生成列
当试图在DataGrid
控件中自定义自动生成的列时,我想做一些简单的事情,例如确保所有数值列值都是右对齐的。为此,我创建了一个DataTemplate
如下:
<DataGrid x:Name="MyGrid" AutoGeneratingColumn="MyGrid_AutoGeneratingColumn">
<DataGrid.Resources>
<DataTemplate x:Key="IntegerTemplate">
<TextBlock Text="{Binding}" HorizontalAlignment="Right"/>
</DataTemplate>
</DataGrid.Resources>
</DataGrid>
然后,在AutoGeneratingColumn
DataGrid
事件处理程序,我要分配这个通用DataTemplate
为CellTemplate
所有积分(即数字)列:
public void MyWindow_AdjustColumnTemplateBasedOnType(
DataGridAutoGeneratingColumnEventArgs e)
{
if (/*This is a column I want to change*/)
{
DataGridTemplateColumn column=new DataGridTemplateColumn();
column.Header=e.PropertyName;
column.CellTemplate=MyGrid.FindResource("IntegerTemplate") as DataTemplate;
e.Column=column;
}
}
问题是TextBlock
的Text
列的值不显示所需的结果。相反,在每个小区其列在看到右对齐值有这个DataTemplate
为CellTemplate
,我看到:
通过设置属性Text
到"{Binding}"
是显然是不正确使用空绑定语法。设置基于路径的绑定确实会产生所需的结果。也就是说,如果我设置了(硬编码的数据路径)使用类似的绑定:
<DataGrid.Resources>
<DataTemplate x:Key="IntegerTemplate">
<!-- Binding hard set to ProductId -->
<TextBlock Text="{Binding ProductId}" HorizontalAlignment="Right"/>
</DataTemplate>
</DataGrid.Resources>
然后一切都很好,但我一般DataTemplate
不再是通用的。相反,它是可重复使用的所有整数列,它只能用于ProductId
列,因为结合被固定在特定数据项的值:
什么是正确的绑定我应该使用,以便通用DataTemplate
实际使用与其关联的列的相应ItemSource
属性中的任何值。
@迈克尔Goldshteyn:我有同样的问题,你有没有找到一个解决方案 –