基于DataGridCell值的触发器

时间:2011-04-30 12:51:14

标签: wpf binding datagridcell

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

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

使用样式触发器时,似乎触发器应用于属性。当我做什么都没有发生时(我假设因为内容比简单的值更多)。

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

我是如何实现这一目标的?

有人有什么想法吗?

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

public class ObjectToBackgroundConverter : IValueConverter

3:ViewModel,它通过按钮点击更改模型中0到1之间的整数值,以触发更改转换器颜色的事件。

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

4:Model实现了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();
    }
  }
}

这是ViewModel:

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)
                               });
    }
  }
}