[英]Get selected Row in DataGrid and Change the background color
每當用戶單擊按鈕時,我想在 DataGrid 中獲取選定的行並更改其背景顏色? 我可以使用 SelectedIndex 屬性獲取所選行的索引,但我不知道如何更改相同的背景。
我在VS2010中使用WPF、C#和.Net 4。
謝謝...
最好對這類事情使用觸發器,但請嘗試以下操作
private void button_Click(object sender, RoutedEventArgs e)
{
DataGridRow dataGridRow = dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex) as DataGridRow;
if (dataGridRow != null)
{
dataGridRow.Background = Brushes.Green;
}
}
編輯
選定的DataGridCells
仍將覆蓋該背景,因此您可能還必須處理該背景,例如使用父DataGridRow
上的Tag
屬性
<DataGrid ...>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}},
Path=Tag}" Value="ChangedBackground">
<Setter Property="Background" Value="Transparent" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
<!--...-->
</DataGrid>
private void button_Click(object sender, RoutedEventArgs e)
{
DataGridRow dataGridRow = dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex) as DataGridRow;
if (dataGridRow != null)
{
dataGridRow.Background = Brushes.Green;
dataGridRow.Tag = "ChangedBackground";
}
}
嘗試這個
//get DataGridRow
DataGridRow row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(RowIndex);
row.Background = Brushes.Red;
你也可以使用這個:
<DataGrid ...>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}},
Path=IsSelected}" Value="true">
<Setter Property="Background" Value="Transparent" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
<!--...-->
DataGridRow 具有 Background 屬性。 這是你需要的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.