[英]Bind to property of a child in XAML
我有一个具有属性Text和BackgroundColor的对象CellContent 。 使用CellContent对象,我创建了一个具有FirstName和LastName属性的Persons列表。 我将此列表绑定到一个DataGrid。 我喜欢做的是根据Brush属性设置背景颜色。
下面的代码对于特定的属性LastName效果很好,但是我也想为FirstName设置它。
<DataGrid x:Name="DG">
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="DataGridCell.Background" Value="{Binding LastName.Background}" />
</Style>
</DataGrid.CellStyle>
</DataGrid>
所以问题是,如何在XAML中绑定到CellContent对象的子级,或者如何用某种通配符替换LastName?
在生成表时,我使用了AutoGeneratingColumn事件来分配Background属性。 现在,DataGrid XAML如下所示:
<DataGrid Name="DG" AutoGeneratingColumn="DG_AutoGeneratingColumn" />
以及后面的代码:
private void DG_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = e.Column.Header;
textColumn.Binding = new Binding(e.Column.Header.ToString());
textColumn.CellStyle = new Style();
textColumn.CellStyle.TargetType = typeof(DataGridCell);
textColumn.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, new Binding(e.Column.Header + ".Background")));
(sender as DataGrid).Columns.Add(textColumn);
// Prevent autogenerating the columns
e.Cancel = true;
}
这当然不是最好的解决方案,但它解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.