c# - 获取 DataGrid 中选定的行并更改背景颜色

标签 c# wpf visual-studio-2010 .net-4.0

每当用户单击按钮时,我想获取 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/

相关文章:

c++ - 并非所有函数都使用 dllexport 导出

visual-studio - 如何关闭 Visual Studio 工具提示?

c# - WCF - 检测响应中的错误

c# - 获取 Memory<byte>/Span<byte> 可变结构的正确方法?

c# - 在 ASP.NET Web 窗体中管理长时间运行的任务的策略

c# - WPF 应用程序在每个系统规模上都具有相同的大小(独立于规模)

c# - 如何获取 SOAP 请求消息的 xml 表示形式?

c# - ListView 对象引用未设置为对象的实例

c# - WPF 拖放按钮

c# - 在 visual studio 2010 中添加安装项目的快捷方式