我试图找出创建样式/触发器以将前景设置为红色的最佳方法,当值 < 0 时。最好的方法是什么?我假设 DataTrigger,但我如何检查负值,我是否必须创建自己的 IValueConverter?
问问题
10099 次
3 回答
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>
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
}
}
于 2010-07-08T15:26:10.740 回答
9
您应该在 ViewModel 中有您的视图特定信息。但是你可以去掉 ViewModel 中的 Style 特定信息。
因此,在 ViewModel 中创建一个返回布尔值的属性
public bool IsMyValueNegative { get { return (MyValue < 0); } }
并在 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>
于 2010-07-09T11:19:17.543 回答
6
对于 Amsakanna 的解决方案,我必须向 Property Setter 添加一个类名:
<Setter Property=" TextBlock .Foreground" Value="Red" />
于 2012-03-14T20:33:11.807 回答