You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改DataSet填充的WPF DataGrid高亮选中单元格样式

问题描述

我已经在后置代码中实现了高亮列的颜色修改,现在需要实现行被选中时对应单元格显示不同颜色的效果,优先通过设计器实现。

原有实现示例

Dim s As Style = New Style(GetType(DataGridCell))
  s.Setters.Add(New Setter(BackgroundProperty, Brushes.LightBlue))
  s.Setters.Add(New Setter(BorderThicknessProperty, New Thickness(0)))
  s.Setters.Add(New Setter(ForegroundProperty, Brushes.Black))
  s.Setters.Add(New Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right))
  DgwRacunStavke.Columns(DgwRacunStavke.IndexKoloneNaOsnovUNaziva("Može da se upiše u refundaciju")).CellStyle = s

首次尝试XAML实现的问题

我尝试在设计器中编写XAML实现但绑定失效,应该是写法有误:

<DataGrid.CellStyle> 
    <Style TargetType="DataGridCell" >
     <Style.Triggers>
      <DataTrigger Binding="{Binding Header}" Value="Može da se upiše u refundaciju"/>
     </Style.Triggers>
     <Setter Property="Background" Value="{StaticResource bojaZaIsticanjeKoloneUGridu}"/>
     <Setter Property="BorderBrush" Value="{StaticResource bojaZaIsticanjeKoloneUGridu}"/>
     <Setter Property="Foreground" Value="{StaticResource bojaFontaZaIsticanjeKoloneUGridu}"/>
    </Style>
   </DataGrid.CellStyle>

后续排查发现需要添加IsSelected属性的触发器来实现选中状态的样式切换。

最终解决方案

XAML代码

<Style x:Key="DataGridCell_Isticanje" TargetType="DataGridCell">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="False">
                <Setter Property="Background" Value="{StaticResource bojaZaIsticanjeKoloneUGridu}"/>
                <Setter Property="BorderThickness" Value="0"/>
                <Setter Property="Foreground" Value="{StaticResource bojaFontaZaIsticanjeKoloneUGridu}"/>
            </Trigger>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="{StaticResource bojaMouseOver}"/>
                <Setter Property="BorderThickness" Value="0"/>
                <Setter Property="Foreground" Value="{StaticResource bojaFontaKadaJeSelektovan}"/>
            </Trigger>
        </Style.Triggers>
    </Style>

后置代码

DGW.Columns(DGW.IndexKoloneNaOsnovUNaziva("Može da se upiše u refundaciju")).CellStyle = FindResource("DataGridCell_Isticanje")

内容的提问来源于stack exchange,提问作者Milos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:18:02