每当用户单击按钮时,我想获取 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";
}
}
关于c# - 获取 DataGrid 中选定的行并更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7077520/