简体   繁体   English

绑定到XAML中孩子的财产

[英]Bind to property of a child in XAML

I have a object CellContent with the properties Text and BackgroundColor . 我有一个具有属性TextBackgroundColor的对象CellContent With the CellContent objects I created a list of Persons with the properties FirstName and LastName . 使用CellContent对象,我创建了一个具有FirstNameLastName属性的Persons列表。 I bound this list to a DataGrid. 我将此列表绑定到一个DataGrid。 What I like to do, is to set the background color according to the Brush property. 我喜欢做的是根据Brush属性设置背景颜色。

The code below works well for the specific property LastName but I want to set it for FirstName too. 下面的代码对于特定的属性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>

So the question is, how do I bind to child of the CellContent object in XAML or how can I replace LastName with some kind of wildcard? 所以问题是,如何在XAML中绑定到CellContent对象的子级,或者如何用某种通配符替换LastName?

I used the AutoGeneratingColumn event to assign the Background property while generating the table. 在生成表时,我使用了AutoGeneratingColumn事件来分配Background属性。 The DataGrid XAML now looks like this: 现在,DataGrid XAML如下所示:

<DataGrid Name="DG" AutoGeneratingColumn="DG_AutoGeneratingColumn" />           

and the code behind: 以及后面的代码:

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;
}

This is certainly not the best solution but it solved my problem. 这当然不是最好的解决方案,但它解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM