【问题标题】:A trigger based on the value of a DataGridCell基于 DataGridCell 值的触发器
【发布时间】:2011-04-30 12:51:14
【问题描述】:

我在数据网格中有一些单元格,当某些列的值为 0 时,我想将某些列中的单元格突出显示为红色。我不知道如何处理。

我看过这个问题:WPF: How to highlight all the cells of a DataGrid meeting a condition?,但没有一个解决方案对我有用。

使用样式触发器时,触发器似乎是要应用于属性的。当我做一些什么都没有发生的事情时(我假设是因为内容不仅仅是一个简单的值)。

在最后一个建议的解决方案中,我遇到了一个编译时问题,这似乎是 VS 中存在一段时间的错误的表现:Custom binding class is not working correctly

有什么想法可以实现吗?

有人有什么想法吗?

【问题讨论】:

    标签: wpf binding datagridcell


    【解决方案1】:

    根据 DataGridCell 的值更改单元格背景颜色的最佳方法是使用转换器为 DataGridTemplateColumn 定义一个 DataTemplate 以更改单元格的背景颜色。此处提供的示例使用 MVVM。

    在以下示例中要搜索的关键部分包括:

    1:将模型中的整数(Factor)转换为颜色的XAML:

    <TextBlock Text="{Binding Path=FirstName}" 
               Background="{Binding Path=Factor, 
                 Converter={StaticResource objectConvter}}" />
    

    2:根据模型中的整数属性返回 SolidColorBrush 的转换器:

    public class ObjectToBackgroundConverter : IValueConverter
    

    3:ViewModel 将 Model 中的整数值更改为 0 到 1 之间,单击 Button 以触发更改 Converter 中颜色的事件。

    private void OnChangeFactor(object obj)
    {
      foreach (var customer in Customers)
      {
        if ( customer.Factor != 0 )
        {
          customer.Factor = 0;
        }
        else
        {
          customer.Factor = 1;
        }
      }
    }
    

    4:模型实现 INotifyPropertyChanged 用于触发事件,通过调用 OnPropertyChanged 来改变背景颜色

    private int _factor = 0;
    public int Factor
    {
      get { return _factor; }
      set
      {
        _factor = value;
        OnPropertyChanged("Factor");
      }
    }
    

    我在回答中提供了此处所需的所有位,但用作 MVVM 模式的基础,包括 ViewModelBase (INotifyPropertyChanged) 和 DelegateCommand,您可以通过 google 找到它们。请注意,我在代码隐藏的构造函数中将 View 的 DataContext 绑定到 ViewModel。如果需要,我可以发布这些额外的内容。

    这是 XAML:

    <Window x:Class="DatagridCellsChangeColor.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:Helpers="clr-namespace:DatagridCellsChangeColor.Converter" 
        Title="MainWindow" 
        Height="350" Width="525">
      <Window.Resources>
        <Helpers:ObjectToBackgroundConverter x:Key="objectConvter"/>
       /Window.Resources>
     <Grid>
      <Grid.RowDefinitions>
       <RowDefinition Height="Auto"/>
       <RowDefinition/>
      </Grid.RowDefinitions>
      <Button Content="Change Factor" Command="{Binding Path=ChangeFactor}"/>
      <DataGrid
       Grid.Row="1"
       Grid.Column="0"
       Background="Transparent" 
       ItemsSource="{Binding Customers}" 
       IsReadOnly="True"
       AutoGenerateColumns="False">
       <DataGrid.Columns>
        <DataGridTemplateColumn
          Header="First Name" 
          Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Path=FirstName}" 
                          Background="{Binding Path=Factor, 
                          Converter={StaticResource objectConvter}}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn
          Header="Last Name" 
          Width="SizeToHeader">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBox Text="{Binding Path=LastName}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
       </DataGrid.Columns>
      </DataGrid>
     </Grid>
    </Window>
    

    这是转换器:

    using System;
    using System.Drawing;
    using System.Globalization;
    using System.Windows.Data;
    using System.Windows.Media;
    using Brushes = System.Windows.Media.Brushes;
    
    namespace DatagridCellsChangeColor.Converter
    {
      [ValueConversion(typeof(object), typeof(SolidBrush))]
      public class ObjectToBackgroundConverter : IValueConverter
      {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
          int c = (int)value;
    
          SolidColorBrush b;
          if (c == 0)
          {
            b = Brushes.Gold;
          }
          else
          {
            b = Brushes.Green;
          }
          return b;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
          throw new NotImplementedException();
        }
      }
    }
    

    这是视图模型:

    using System.Collections.ObjectModel;
    using System.Windows.Input;
    using DatagridCellsChangeColor.Commands;
    using DatagridCellsChangeColor.Model;
    
    namespace DatagridCellsChangeColor.ViewModel
    {
      public class MainViewModel : ViewModelBase
      {
        public MainViewModel()
        {
          ChangeFactor = new DelegateCommand<object>(OnChangeFactor, CanChangeFactor);
        }
    
        private ObservableCollection<Customer> _customers = Customer.GetSampleCustomerList();
        public ObservableCollection<Customer> Customers
        {
          get
          {
             return _customers;
          }
        }
    
        public ICommand ChangeFactor { get; set; }
        private void OnChangeFactor(object obj)
        {
          foreach (var customer in Customers)
          {
            if ( customer.Factor != 0 )
            {
              customer.Factor = 0;
            }
            else
            {
              customer.Factor = 1;
            }
          }
        }
    
        private bool CanChangeFactor(object obj)
        {
          return true;
        }
      }
    }
    

    这是模型:

    using System;
    using System.Collections.ObjectModel;
    using DatagridCellsChangeColor.ViewModel;
    
    namespace DatagridCellsChangeColor.Model
    {
      public class Customer : ViewModelBase
      {
        public Customer(String first, string middle, String last, int factor)
        {
          this.FirstName = first;
          this.MiddleName = last;
          this.LastName = last;
          this.Factor = factor;
        }
    
        public String FirstName { get; set; }
        public String MiddleName { get; set; }
        public String LastName { get; set; }
    
        private int _factor = 0;
        public int Factor
        {
          get { return _factor; }
          set
          {
            _factor = value;
            OnPropertyChanged("Factor");
          }
        }
    
        public static ObservableCollection<Customer> GetSampleCustomerList()
        {
          return new ObservableCollection<Customer>(new Customer[4]
                                   {
                                     new Customer("Larry", "A", "Zero", 0),
                                     new Customer("Bob", "B", "One", 1),
                                     new Customer("Jenny", "C", "Two", 0),
                                     new Customer("Lucy", "D", "THree", 2)
                                   });
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 2012-05-05
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多