Mic*_*eyn 4 wpf wpf-controls wpfdatagrid
在阅读了关于如何自定义自动生成列的优秀文章后,我遇到了一个问题。
在尝试自定义控件中自动生成的列时DataGrid,我想做一些简单的事情,例如确保所有数字列值都右对齐。为此,我创建了一个DataTemplate如下:
<DataGrid x:Name="MyGrid" AutoGeneratingColumn="MyGrid_AutoGeneratingColumn">
<DataGrid.Resources>
<DataTemplate x:Key="IntegerTemplate">
<TextBlock Text="{Binding}" HorizontalAlignment="Right"/>
</DataTemplate>
</DataGrid.Resources>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
然后,在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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是Text列的值TextBlock没有显示出想要的结果。而不是在每个单元格中看到正确对齐的值,其列将 thisDataTemplate作为它的CellTemplate,我看到:

使用空绑定语法由属性设置Text到"{Binding}"是显然是不正确。设置基于路径的绑定确实会产生所需的结果。也就是说,如果我使用以下内容设置(硬编码数据路径)绑定:
<DataGrid.Resources>
<DataTemplate x:Key="IntegerTemplate">
<!-- Binding hard set to ProductId -->
<TextBlock Text="{Binding ProductId}" HorizontalAlignment="Right"/>
</DataTemplate>
</DataGrid.Resources>
Run Code Online (Sandbox Code Playgroud)
然后一切都很好,但我的泛型DataTemplate不再是泛型了。它不能用于所有整数列,而是只能用于ProductId列,因为绑定固定为该特定数据项的值:

我应该使用的正确绑定是什么,以便泛型DataTemplate实际上使用ItemSource与其关联的列的相应属性中的任何值。
小智 5
我相信样式会在这里解决您的问题。
private void MyGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (/*This is a column I want to change*/)
{
DataGridColumn column = e.Column;
column.CellStyle = MyGrid.FindResource("IntegerTemplate") as Style;
}
}
Run Code Online (Sandbox Code Playgroud)
在 XAML 中,您可以编写
<Style TargetType="DataGridCell" x:Key="IntegerTemplate">
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7376 次 |
| 最近记录: |