【问题标题】:WPF DataGrid: How To Keep Selected Rows Highlighted?WPF DataGrid:如何突出显示选定的行?
【发布时间】:2015-10-31 02:03:08
【问题描述】:

我的 WPF 项目中的同一个窗口上有多个 DataGrid 控件。当我单击网格中的一行时,它会突出显示。当我单击另一个网格中的一行时,该行突出显示并且第一个网格中的行变得非常微弱地突出显示。如何设计此窗口,以便每个网格可以同时突出显示选定的行?我的项目是在 .NET 4.0 中构建的,因此 InactiveSelectionHighlightBrushKey 似乎不起作用。我正在使用下面的代码,它基本上可以工作,除非当我单击不同的网格时,前一个网格将行文本颜色更改为黑色而不是白色。我尝试将 ControlTextBrushKey 设置为白色,但这使得网格中的每一行都变成白色,这意味着未选中的行因为不可见,因为背景也是白色的。是否有更优雅的方法来创建用户控件或从 DataGrid 类继承,因为我需要在项目中多次插入此代码。

                <DataGrid Name="dgStores" >
                    <DataGrid.Resources>
                        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{x:Static Colors.DodgerBlue}"/>
                        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="White"/>
                        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static Colors.DodgerBlue}"/>
                    </DataGrid.Resources>
                </DataGrid>

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    试试这个:

    <DataGrid ItemsSource="{Binding Items}">
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Setter Property="Background" Value="White" />
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="Blue"/>
                        <Setter Property="Foreground" Value="White"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
    </DataGrid>
    

    【讨论】:

    • 那行不通。它的行为基本上就像一个普通的网格。当我单击一行时,它以蓝色突出显示。当我单击第二个网格中的一行时,第一个网格中突出显示的行变得非常微弱地突出显示。
    • 好的,我再看看
    【解决方案2】:

    使用 Style.Triggers 为 DataGridCell 设置 IsSelected 颜色。

    <Window.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{x:Static SystemColors.HighlightBrush}"></Setter>
                    <Setter Property="Foreground" Value="{x:Static SystemColors.HighlightTextBrush}"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    

    【讨论】:

      猜你喜欢
      • 2013-06-11
      • 1970-01-01
      • 2013-12-20
      • 2011-10-01
      • 2023-03-29
      • 1970-01-01
      • 2016-06-13
      • 2011-05-27
      • 1970-01-01
      相关资源
      最近更新 更多