WPF TextBlock Negative Number In Red

我的梦境 提交于 2020-01-02 02:42:08

问题


I am trying to figure out the best way to create a style/trigger to set foreground to Red, when value is < 0. what is the best way to do this? I'm assuming DataTrigger, but how can I check for negative value, do i have to create my own IValueConverter?


回答1:


If you are not using an MVVM model (where you may have a ForegroundColor property), then the easiest thing to do is to create a new IValueConverter, binding your background to your value.

In MyWindow.xaml:

<Window ...
    xmlns:local="clr-namespace:MyLocalNamespace">
    <Window.Resources>
        <local:ValueToForegroundColorConverter x:Key="valueToForeground" />
    <Window.Resources>

    <TextBlock Text="{Binding MyValue}"
               Foreground="{Binding MyValue, Converter={StaticResource valueToForeground}}" />
</Window>

ValueToForegroundColorConverter.cs

using System;
using System.Windows.Media;
using System.Windows.Data;

namespace MyLocalNamespace
{
    class ValueToForegroundColorConverter: IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            SolidColorBrush brush = new SolidColorBrush(Colors.Black);

            Double doubleValue = 0.0;
            Double.TryParse(value.ToString(), out doubleValue);

            if (doubleValue < 0)
                brush = new SolidColorBrush(Colors.Red);

            return brush;
        }

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

        #endregion
    }
}



回答2:


You should have your view specific information in your ViewModel. But you can get rid of the Style specific information in the ViewModel.

Hence create a property in the ViewModel which would return a bool value

public bool IsMyValueNegative { get { return (MyValue < 0); } }

And use it in a DataTrigger so that you can eliminate the ValueConverter and its boxing/unboxing.

<TextBlock Text="{Binding MyValue}"> 
  <TextBlock.Style> 
    <Style> 
      <Style.Triggers> 
        <DataTrigger Binding="{Binding IsMyValueNegative}" Value="True"> 
          <Setter Property="Foreground" Value="Red" /> 
        </DataTrigger> 
      </Style.Triggers> 
    </Style> 
  </TextBlock.Style> 
</TextBlock> 



回答3:


For Amsakanna's solution I had to add a class name to the Property Setter:

<Setter Property="TextBlock.Foreground" Value="Red" />



来源:https://stackoverflow.com/questions/3205096/wpf-textblock-negative-number-in-red

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!