我有一个DataGrid和一个CellTemplate,其中我通过PropertyDescriptors动态地创建列。我使用这种方法:http://paulstovell.com/blog/dynamic-datagrid列生成工作,正确的内容到达正确的单元格。
我的问题在于当我改变提供给单元格的内容时。包含多个属性的自定义类的“‘string”或“int”。CellTemplate不会绑定到contentclass中的属性。
内容类:
public class ContentWrapper
{
public Color Color{ get; set; }
public String Text { get; set; }
public String Comment { get; set; }
}cellTemplate:
<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;
}
}
}发布于 2013-09-19 12:15:33
噢..。我在这上面工作了两天,一小时后我就解决了这个问题。
我将列类型改为嵌套类型的DataGridTemplateColumn,手动加载单元格模板和绑定。
发布于 2013-09-19 12:23:43
为解决你的问题做得好。
我不是试图回答你的问题,而是简单地提出一些建议:
您似乎试图从Bind内部对数据实例属性进行DataGrid ControlTemplate.那不是真正的目的。Template属性允许我们定义控件的外观。您应该将项Style和数据Binding放在定义数据项呈现方式的ItemsTemplate中。这是一个重要的区别。
来自MSDN:
ItemsTemplate属性-获取或设置用于显示每个项的DataTemplate。 属性-获取或设置控件模板。ControlTemplate指定控件的外观
https://stackoverflow.com/questions/18892844
复制相似问题