【发布时间】:2012-02-19 17:32:27
【问题描述】:
在阅读了关于如何Customize Auto-Generated Columns 的优秀文章后,我遇到了一个问题。
在尝试自定义 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 属性中的任何值。
【问题讨论】:
-
@Michael Goldshteyn:我也有同样的问题,你找到解决办法了吗?
标签: wpf wpf-controls wpfdatagrid