【问题标题】:wpf trigger not effective on style set in codewpf 触发器对代码中设置的样式无效
【发布时间】:2018-01-28 15:21:18
【问题描述】:

在 Resources.Xaml 中,我从 Datagrid Cell 设置样式

<Style TargetType="DataGridCell" >
    <Style.Triggers>
        <Trigger  Property="DataGridCell.IsSelected"  Value="True">
            <Setter Property="Background" Value="CornflowerBlue" />
            <Setter Property="Foreground" Value="White" />
        </Trigger>
    </Style.Triggers>
</Style>

在特定的 DataGrid 列中,我手动设置了前景

 Sub New()
        FontWeight = FontWeights.Bold
        Foreground = Brushes.Blue
 End Sub

当单元格被选中时,背景剂量由触发器改变,而前景剂量不变

我相信这是因为我在代码中设置了前景

我能做些什么来解决这个问题?

注意:我无法为 xaml 中的列设置前景

【问题讨论】:

    标签: wpf xaml eventtrigger


    【解决方案1】:

    写作Foreground = Brushes.Blue 你为前台依赖属性设置了本地值。本地值的优先级高于来自触发器的设置器值。我建议为 DataGridCell 创建一个命名样式,派生自基于样式,并在代码中应用派生样式:

    <Style TargetType="DataGridCell" >
        <Style.Triggers>
            <Trigger  Property="DataGridCell.IsSelected"  Value="True">
                <Setter Property="Background" Value="CornflowerBlue" />
                <Setter Property="Foreground" Value="White" />
            </Trigger>
        </Style.Triggers>
    </Style>
    
    <Style x:Key="BlueCell" TargetType="DataGridCell" BasedOn="{x:Type DataGridCell}">
        <Setter Property="Foreground" Value="Blue" />
        <Setter Property="FontWeight" Value="Bold" />
    </Style>
    
    Sub
       CellStyle = (Style)datagrid.FindResource("BlueCell");
    End Sub
    

    由于缺乏 vb.net 知识,我正在使用 c# 语法。代码调用 DataGrid 的 FindResource 方法来检索“BlueCell”样式,并在转换为 Style 类型后分配给列的 CellStyle

    【讨论】:

    • @YonatanTuchinsky,太好了。如果您必须对某些内容进行重大更改以使事情正常进行,请随时提出对此答案的改进(建议“编辑”)
    • 我按照您的建议做了一些更改,将原始样式设置为一个键并基于该键 - 我还将它添加到应用程序 Resouces.xaml 并从那里获取资源 Application.Current.Resources("NewStyle")跨度>
    猜你喜欢
    • 2011-09-30
    • 2019-07-22
    • 2012-03-14
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    相关资源
    最近更新 更多