1

データグリッドにいくつかのセルがあり、値が 0 の場合に特定の列のセルを赤で強調表示したいと考えています。これにアプローチする方法がわかりません。

私はこの質問を見てきました: WPF: 条件を満たしている DataGrid のすべてのセルを強調表示する方法は? しかし、どの解決策もうまくいきませんでした。

スタイルトリガーを使用すると、トリガーはプロパティに適用されるようになっているようです。何も起こらないようなことをすると(コンテンツには単純な値以上のものがあるためだと思います)。

最後に提案された解決策で、コンパイル時の問題が発生しました。これは、VS にしばらくの間存在していたバグの兆候であると思われました:カスタム バインディング クラスが正しく機能していません。

これを達成する方法はありますか?

誰にもアイデアはありますか?

4

1 に答える 1

1

DataGridCell の値に基づいてセルの背景色を変更する最良の方法は、Converter を使用して 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: モデルの整数値を 0 から 1 の間で変更する ViewModel は、ボタン クリックからコンバーターの色を変更するイベントを発生させます。

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

4: モデルは、OnPropertyChanged を呼び出して背景色を変更するイベントを発生させるために使用される INotifyPropertyChanged を実装します。

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

ViewModelBase (INotifyPropertyChanged) と Google 経由で見つけることができる DelegateCommand を含む MVVM パターンの基盤として使用されるコア部分を除いて、ここで必要なすべてのビットを私の回答で提供しました。コード ビハインドのコンストラクターで、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)
                               });
    }
  }
}
于 2011-05-01T02:32:05.087 に答える