【问题标题】:WPF datagrid Cell color depending on preivous cell valueWPF datagrid 单元格颜色取决于先前的单元格值
【发布时间】:2011-09-04 04:15:07
【问题描述】:

背景。

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

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

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

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

代码:

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

【问题讨论】:

    标签: wpf datagrid colors cell


    【解决方案1】:

    要更改 DataGrid 单元格中的颜色,我建议如下:

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

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

    【讨论】:

      【解决方案2】:

      我认为问题不在于数据网格,而在于您绑定到的对象。如果您绑定到数据表,则旧值是内置的(DataRowVersion)。如果你有其他实体对象,那么这个实体需要支持原始值和修改值。

      【讨论】:

      • 谢谢,但你能给我举个例子吗?作为 WPF 新手,我不明白如何将对象绑定到数据网格。
      • 我不认为DataRowVersion 是解决方案。当您需要访问从数据库接收的版本和本地修改版本时,这很有用。 OP 想要的是来自数据库的旧值和来自数据库的新值。
      猜你喜欢
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多