【问题标题】:DataTrigger When Greater Than a Number大于数字时的 DataTrigger
【发布时间】:2016-05-13 14:05:23
【问题描述】:

我有一个名为 OperativeCount 的值。当这个数字大于 10 时,我希望 DataGridColumn 的颜色发生变化。类似的东西;

<DataGrid.Resources>
    <Style x:Key="DGCellStyle" TargetType="DataGridCell">
        <Style.Triggers>
            <DataTrigger Binding="{Binding OperativeCount}" Value=">10">
                <Setter Property="FontWeight" Value="Bold"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

显然,目前Value="&gt;10" 不起作用,但基本上这就是我想做的。

【问题讨论】:

标签: c# wpf xaml data-binding datagrid


【解决方案1】:

用于 WPF 的 Blend SDK 可以非常快速地完成它,而无需任何代码。查看DataTrigger (Blend SDK for WPF)。使用 ChangePropertyAction 作为行为。

<ei:DataTrigger Binding="{Binding OperativeCount}" Comparison="GreaterThan" Value="10">
  <ei:ChangePropertyAction PropertyName="FontWeight" >
     <ei:ChangePropertyAction.Value>
       <FontWeight>Bold</FontWeight>
     </ei:ChangePropertyAction.Value>
   </ei:ChangePropertyAction>
</ei:DataTrigger>

别费心了,让 Blend 来处理。

【讨论】:

【解决方案2】:

如果您不需要重用此组件或使其“通用”,则可以使用以下更简单且最集中的解决方案。

使用此代码创建转换器:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace WpfApplication1
{
    public class CountToFontWeightConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return DependencyProperty.UnsetValue;

            var count = (int)value;

            if (count > 10)
                return FontWeights.Bold;
            else
                return FontWeights.Normal;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

然后这样使用:

<DataGrid.Resources>

  <local:CountToFontWeightConverter x:Key="CountToFontWeightConverter"/>

  <Style TargetType="{x:Type DataGridCell}" x:Key="DGCellStyle">
    <Setter Property="FontWeight"
            Value="{Binding OperativeCount,
              Converter={StaticResource CountToFontWeightConverter}}"/>
  </Style>

</DataGrid.Resources>

显然,如果 OperativeCount 属性在您的应用程序的生命周期内发生更改,它必须通过 INotifyPropertyChanged 实现或通过 Reactive 库发出更改通知。

您可以通过将10 的限制作为转换器的参数来概括此解决方案,而不是在转换器本身内部对其进行硬编码,因此您可以在具有不同限制的多个地方使用它。

【讨论】:

    猜你喜欢
    • 2018-04-07
    • 2013-07-15
    • 2016-03-05
    • 2021-06-20
    • 1970-01-01
    • 2014-11-05
    • 2023-03-12
    • 2013-12-03
    • 1970-01-01
    相关资源
    最近更新 更多