根据条件更改ListView Forecolor

时间:2013-12-26 17:52:01

标签: c# .net wpf xaml data-binding

我是WPF的新手,所以目前对这个概念非常困惑。 我有一个库存程序,我想根据股票价格上涨或下跌来改变该单元格的前景色。

这是我目前的代码(省略了几件事):

public class Stock : INotifyPropertyChanged
{
    public Stock()
    {
        DaysLow = 0;
        DaysHigh = 0;
    }

    public List<string[]> StockInformation = new List<string[]>();

    public string Symbol { get; set; }

    private double _Bid;
    public double Bid
    {
        get { return _Bid; }
        set
        {
            // If _Bid < value, change fore color
            _Bid = value;
            DisplayCurrentPrice = String.Format("{0} / {1}", value, Ask);

        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }

    public override string ToString()
    {
        return Symbol;
    }
}

XAML:

        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="Height" Value="26" />
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.View>
            <GridView AllowsColumnReorder="False">
                <GridViewColumn Header="Symbol" DisplayMemberBinding="{Binding Path=Symbol}" Width="120" />
                <GridViewColumn Header="Bid / Ask" DisplayMemberBinding="{Binding Path=DisplayCurrentPrice}" Width="125" />
                <GridViewColumn Header="D.High" DisplayMemberBinding="{Binding Path=DaysHigh}" Width="75" />
                <GridViewColumn Header="D.Low" DisplayMemberBinding="{Binding Path=DaysLow}" Width="75" />
                <GridViewColumn Header="Year Low/High" DisplayMemberBinding="{Binding Path=DisplayYearPrice}" Width="100" />
            </GridView>
        </ListView.View>
        <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Details" Click="CM_Details_Click"></MenuItem>
            </ContextMenu>
        </ListView.ContextMenu>
    </ListView>

那么我能在这里做些什么来实现我的目标呢?感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

以下是我代表StockModel课程的方式:

class StockModel : INotifyPropertyChanged
{
    // NOTE: You must implement PropertyChanged notification for these properties...
    public string Symbol { get; set; }
    public decimal Bid { get; set; }
    public decimal Delta { get; set; }  // Change in price over time, +/-

    // Any additional properties you may want here...
}

现在,WPF的美妙之处在于IValueConverter类。这些类允许您使用您提供的逻辑将值从一种类型“转换”为另一种类型。

在我们的示例中,我们希望将ListViewItem.Foreground颜色绑定到StockModel.Delta值。正非零delta值应该给我们Green,负的非零delta值应该给我们Red。零可以保持BlackWhite(取决于主题的对比度)。

那么我们如何完成这样的事情呢?我们需要创建一个实现StockColorConverter的{​​{1}}类:

IValueConverter

现在,您需要在XAML中正确连接它。首先,假设您在sealed class StockColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // Convert a delta value to a brush color. var deltaValue = System.Convert.ToDecimal(value); if (deltaValue > 0) return Brushes.Green; // Positive else if (deltaValue < 0) return Brushes.Red; // Negative else return Brushes.Black; // Zero } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // We can't convert a color to a delta value! This will never be used anyhow. throw new NotSupportedException(); } } 文件中执行此操作。您需要在现有命名空间之后添加项目的命名空间:

MainWindow.xaml

然后,创建(或追加)xmlns:my="clr-namespace:WpfApplication1"

Window.Resources

使用<Window.Resources> <my:StockColorConverter x:Key="StockColorConverter"/> </Window.Resources> 来处理DataTemplate的布局要容易得多。 ListViewItem确定每个项目的显示方式以及应显示的内容:

DataTemplate

您可以看到我们将 <ListView.ItemTemplate> <!-- These are StockModel objects as our data! --> <DataTemplate> <TextBlock Text="{Binding Symbol}" Foreground="{Binding Delta, Converter={StaticResource StockColorConverter}}"/> </DataTemplate> </ListView.ItemTemplate> 绑定到TextBlock.Foreground。通常这不起作用,因为StockModel.Delta不等同于decimal对象。但是,使用我们创建的Brush,我们可以轻松应用条件格式。

答案 1 :(得分:0)

您可以在c#

中添加此内容
public bool ChangeColor {get; set;}

private double _Bid;
public double Bid
{
    get { return _Bid; }
    set
    {
         If (_Bid < value)//, change fore color
              ChangeColor = True;
        _Bid = value;
        DisplayCurrentPrice = String.Format("{0} / {1}", value, Ask);

    }
}

然后在xaml

       <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="Height" Value="26" />
                <Style.Triggers>
                   <DataTrigger Binding="{Binding Path=ChangeColor}" Value="True">
                      <Setter Property="ForeColor" Value="Red"/>
                   </DataTrigger >
                </Style.Triggers>
            </Style>
        </ListView.ItemContainerStyle>