[英]How to set background for single cell of datagrid wpf not single row?
我有這段代碼,我想更改數據網格的單個單元格的背景。
在我的代碼中,更改行的背景。
<DataGrid x:Name="dg">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding Place}"
Value="true">
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
和C#代碼:
DataTable dt = new DataTable();
dt.Columns.Add("Time", typeof(string));
dt.Columns.Add("Place", typeof(string));
dt.Rows.Add( "23:00", "true");
dt.Rows.Add( "21:00", "true");
dt.Rows.Add( "19:00", "false");
dg.ItemsSource = dt.AsDataView();
我搜索了一下,並為DataGridView編寫了以下代碼:
this.dataGridView1.Rows[0].Cells[1].Style.ForeColor = System.Drawing.Color.Red;
但這不適用於wpf的DataGrid。
如何更改此代碼為DataGrid WPF?
您可以通過編程方式設置單元格背景色。
DataGridRow dgRow = mydatagrid.ItemContainerGenerator.ContainerFromIndex(mydatagrid.SelectedIndex) as DataGridRow;
DataGridCell cell = mydatagrid.Columns(2).GetCellContent(dgRow).Parent as DataGridCell;
cell.Background = New SolidColorBrush(Colors.Blue);
這個問題的答案是用C#編寫以下代碼:
dataGrid.UpdateLayout();
DataGridRow dgRow = mydatagrid.ItemContainerGenerator.ContainerFromIndex(mydatagrid.SelectedIndex) as DataGridRow;
DataGridCell cell = mydatagrid.Columns(2).GetCellContent(dgRow).Parent as DataGridCell;
cell.Background = New SolidColorBrush(Colors.Blue);
DataTrigger綁定到屬性Place,並檢查值“ true”。 我還沒有使用過數據表,但是您似乎試圖綁定到字符串類型的“位置”列。 數據網格期望Place為bool或值為“ true”(字符串)。 畢竟,如果您更改了綁定屬性的值,則必須通知該屬性的更改( 此處 )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.