WPF TextBlock红色负数

Mic*_*han 8 wpf triggers styles datatrigger textblock

我试图找出创建样式/触发器以将前景设置为红色的最佳方法,当值<0时,最好的方法是什么?我假设DataTrigger,但我如何检查负值,我是否必须创建自己的IValueConverter?

Won*_*ane 14

如果您没有使用MVVM模型(您可能具有ForegroundColor属性),那么最简单的方法是创建一个新的IValueConverter,将您的背景绑定到您的值.

在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>
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 更灵活的解决方案是使用转换器来确定值是否<0并返回布尔值而不是输出固定颜色.然后,您可以将其与DataTrigger一起使用,并在Setters中进行所需的UI更改.如果您稍后决定需要将文本设置为粗体而不是红色,并将UI保留在XAML所属的位置,那么这样做会更加灵活. (3认同)
  • @LnDCobra:它将与MVVM一起使用.我认为Wonko的意思是,使用MVVM,您可以选择在viewmodel上公开ForegroundColor属性,而不是使用ValueConverter. (2认同)

Ams*_*nna 8

您应该在ViewModel中拥有视图特定信息.但是你可以摆脱ViewModel中的Style特定信息.

因此在ViewModel中创建一个属性,它将返回一个bool值

public bool IsMyValueNegative { get { return (MyValue < 0); } }
Run Code Online (Sandbox Code Playgroud)

并在DataTrigger中使用它,以便您可以消除ValueConverter及其装箱/拆箱.

<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> 
Run Code Online (Sandbox Code Playgroud)


Eri*_* K. 6

对于Amsakanna的解决方案,我必须在Property Setter中添加一个类名:

<Setter Property =“ TextBlock .Foreground” Value =“ Red” />