c# - DatagridRow IsSelected 不完全工作

标签 c# wpf xaml datagrid

我目前正在设计我的应用程序 (WPF),并且正在尝试更改 DatagridRowIsSelected 的设计。

XAML:

<Style TargetType="DataGridRow" BasedOn="{StaticResource {x:Type DataGridRow}}">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
             <Setter Property="Foreground" Value="{StaticResource ForegroundSelectedRow}"/>
             <Setter Property="Background" Value="{StaticResource BackgroundSelectedRow}"/>
        </Trigger>
    </Style.Triggers>
</Style>

当我将焦点放在应用程序上时,此代码可以正常工作,但是当我使用 DataGrid 单击 View 外时,我会丢失前景(它采用另一种颜色),但背景是仍然是相同的...

我不明白如何只有一个可以工作,而另一个却不能......有人知道为什么吗?

编辑 1:

我没有任何 DataGrid.Resources。我在 App.xaml 中设置了所有样式:

<Style x:Key="DataGridStyle" TargetType="DataGrid" BasedOn="{StaticResource {x:Type DataGrid}}">
    <Setter Property="AlternationCount" Value="2"/>
    <Setter Property="AutoGenerateColumns" Value="False"/>
    <Setter Property="IsReadOnly" Value="True"/>
    <Setter Property="CanUserSortColumns" Value="True"/>
    <Setter Property="CanUserAddRows" Value="False"/>
</Style>

我将它绑定(bind)到我的 DataGrid

<DataGrid ItemsSource="{Binding Collects}" Style="{StaticResource DataGridStyle}" ColumnHeaderStyle="{StaticResource DGHeaderMargin}"/>

最佳答案

您可以将 TargedType 更改为 DataGridCell 而不是 DataGridRow (WPF 4.0)

<DataGrid.Resources>
 <Style TargetType="{x:Type dg:DataGridCell}">
    <Style.Triggers>
        <Trigger Property="dg:DataGridCell.IsSelected" Value="True">
            <Setter Property="Foreground" Value="{StaticResource ForegroundSelectedRow}"/>
            <Setter Property="Background" Value="{StaticResource BackgroundSelectedRow}"/>
        </Trigger>
    </Style.Triggers>
</Style>

解决方案2

    <DataGrid.Resources> 
        <Style TargetType="DataGridRow"> 
            <Style.Resources> 
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red"/>                                  
            </Style.Resources> 
        </Style> 
   </DataGrid.Resources> 

关于c# - DatagridRow IsSelected 不完全工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41139975/

相关文章:

c# - 如何去掉字符串中的\r\n

wpf - 根据 ListBox 中的索引设置 ListBoxItem 的样式

c# - 将按键事件路由到其他控件

wpf - 将 double 绑定(bind)到文本框

c# - 如何在不创建 List<string> 的情况下将图像源绑定(bind)到路径列表?

c# - WPF 中静态属性的数据绑定(bind)

c# - 为什么我在 C# 中需要分部类和虚方法?

c# - 如何存储和恢复无限世界?

c# - 在列表中查找子类

wpf - FrameworkElementFactory 必须位于此操作的密封模板中