簡體   English   中英

綁定到XAML中孩子的財產

[英]Bind to property of a child in XAML

我有一個具有屬性TextBackgroundColor的對象CellContent 使用CellContent對象,我創建了一個具有FirstNameLastName屬性的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM