WPF datagrid 单元格颜色取决于先前的单元格值

标签 wpf datagrid colors cell

背景。

我正在开发一个股票交易应用程序。
其中显然有市场观察。
我正在使用 Datagrid 开发这个市场观察.

网格是做什么的?
它显示股票的价格点。
每次股票值(value)增加时,特定的单元格前景变为绿色
如果它减少它会变成红色。

我做了什么?
我尝试使用值转换器方法和多重绑定(bind)

问题。
值转换器仅给出当前值。
我如何将旧值传递给该转换器。

代码:

 <wpfTlKit:DataGrid.CellStyle>
            <Style TargetType="{x:Type wpfTlKit:DataGridCell}">
                <Setter Property="Background">
                    <Setter.Value>
                        <MultiBinding Converter="{StaticResource  myHighlighterConverter}" 
                                      >
                            <MultiBinding.Bindings>
                                <Binding RelativeSource="{RelativeSource Self}"></Binding>
                                <Binding Path="Row" Mode="OneWay"></Binding>
                                <Binding ElementName="OldData" Path="Rows"></Binding>
                            </MultiBinding.Bindings>
                        </MultiBinding>
                    </Setter.Value>
                </Setter>
            </Style>
        </wpfTlKit:DataGrid.CellStyle>

转换器
public class HighlighterConverter : IMultiValueConverter
{
    #region Implementation of IMultiValueConverter

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[1] is DataRow)
        {
            //Change the background of any cell with 1.0 to light red.
            var cell = (DataGridCell)values[0];
            var row = (DataRow)values[1];
            var columnName = cell.Column.SortMemberPath;

            if (row[columnName].IsNumeric() && row[columnName].ToDouble() == 1.0)
                return new SolidColorBrush(Colors.LightSalmon);

        }
        return SystemColors.AppWorkspaceColor;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }

    #endregion
}

public static class Extensions
{
    public static bool IsNumeric(this object val)
    {
        double test;
        return double.TryParse(val.ToString(), out test);
    }

    public static double ToDouble(this object val)
    {
        return Convert.ToDouble(val);
    }
}

最佳答案

要更改 DataGrid 单元格中的颜色,我建议执行以下操作:

构建一个实现 INotifyPropertyChanged 的​​模型,该模型包含当前和以前的价格以及反射(reflect)价格变化的属性(我已在此答案的末尾附加了完整模型)。

public double ChangeInPrice
{
  get
  {
    return CurrentPrice - PreviousPrice;
  }
}

并使用转换器根据价格变化在 DataGrid 中设置 CellTemplate 的背景。
注意:当价格值发生变化时,INotifyPropertyChanged 有助于改变单元格的颜色。
<DataGridTemplateColumn.CellTemplate>
  <DataTemplate>
    <TextBlock 
      Text="{Binding Path=CurrentPrice}" 
      Background="{Binding Path=ChangeInPrice, Converter={StaticResource backgroundConverter}}" >
    </TextBlock>
  </DataTemplate>
</DataGridTemplateColumn.CellTemplate>


[ValueConversion(typeof(object), typeof(SolidBrush))]
public class ObjectToBackgroundConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    SolidColorBrush b = Brushes.White; 

    try
    {
      double stock = (double)value;
      if (stock > 0)
      {
        b = Brushes.Green;
      }
      else if (stock < 0)
      {
        b = Brushes.Red;
      }
    }
    catch (Exception e)
    {
    }  

    return b;
  }

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

这是完整的完整模型:
public class Stock : INotifyPropertyChanged
{
  public Stock(string stockName, double currentPrice, double previousPrice)
  {
    this.StockName = stockName;
    this.CurrentPrice = currentPrice;
    this.PreviousPrice = previousPrice;
  }

  private string _stockName;
  public String StockName
  {
    get { return _stockName; }
    set
    {
      _stockName = value;
      OnPropertyChanged("StockName");
    }
  }

  private double _currentPrice = 0.00;
  public double CurrentPrice
  {
    get { return _currentPrice; }
    set
    {
      _currentPrice = value;
      OnPropertyChanged("CurrentPrice");
      OnPropertyChanged("ChangeInPrice");
    }
  }

  private double _previousPrice = 0.00;
  public double PreviousPrice
  {
    get { return _previousPrice; }
    set
    {
      _previousPrice = value;
      OnPropertyChanged("PreviousPrice");
      OnPropertyChanged("ChangeInPrice");
    }
  }

  public double ChangeInPrice
  {
    get
    {
      return CurrentPrice - PreviousPrice;
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
    PropertyChangedEventHandler handler = PropertyChanged;

    if (handler != null)
    {
      handler(this, new PropertyChangedEventArgs(propertyName));
    }
  }
}

关于WPF datagrid 单元格颜色取决于先前的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6165745/

相关文章:

c# - WPF DataGrid 分组与总和和其他字段

javascript - SlickGrid 中可以使用可变行高吗?

c# - EventSourceException 异常会淹没调试 session 并减慢进程。怎么修?

c# - WPF 和 RibbonControlsLibrary 抛出 BindingExpression 路径错误,甚至不使用绑定(bind)?

wpf - 在 DataGrid 中捕获 DoubleClick

Java JTabbedPane 插入颜色

android - 如何将 ARGB 格式(例如 0xFFFF0000)值分配给 Kotlin INT

visual-studio-2008 - Resharper 4.5 打破了我的配色方案

c# - 如何在 WPF 中改变 Canvas 的位置?

c# - 如何在 WPF 中的多显示器显示上定位窗口?