我有一个带有 CellTemplate 的 DataGrid,我在其中通过 PropertyDescriptors 动态创建列。我正在使用这种方法: http: //paulstovell.com/blog/dynamic-datagrid列生成工作,正确的内容到达正确的单元格。
我的问题在于当我更改从 ex 提供给单元格的内容时。'string' 或 'int' 到包含多个属性的自定义类。CellTemplate 不会绑定到内容类中的属性。
内容类:
public class ContentWrapper
{
public Color Color{ get; set; }
public String Text { get; set; }
public String Comment { get; set; }
}
单元格模板:
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid ToolTip="{Binding Comment}"
Background="{Binding Color, Converter={StaticResource ColorToBrushConverter}}">
<TextBlock Text="{Binding Text}"
VerticalAlignment="Bottom"
HorizontalAlignment="Left"/>
<Polygon Visibility="{Binding Comment, Converter={StaticResource CommentVisibleConverter}, FallbackValue=Hidden}"
HorizontalAlignment="Right"
Points="0,0 6,0 6,6"
VerticalAlignment="Top">
<Polygon.Fill>
<SolidColorBrush Color="Red" />
</Polygon.Fill>
</Polygon>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
如何使 CellTemplate 能够支持自定义类并绑定到它的属性?还是有更简单的方法?
编辑 列生成是这样的:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
var property = e.PropertyDescriptor as Property;
if (property != null)
{
var binding = new Binding() { Path = new PropertyPath(property), Mode = property.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay };
var dataGridBoundColumn = e.Column as DataGridBoundColumn;
if (dataGridBoundColumn != null)
dataGridBoundColumn.Binding = binding;
else
{
var dataGridComboBoxColumn = e.Column as DataGridComboBoxColumn;
if (dataGridComboBoxColumn != null)
dataGridComboBoxColumn.SelectedItemBinding = binding;
}
}
}