【发布时间】:2011-03-13 09:59:57
【问题描述】:
我正在尝试找出创建样式/触发器以将前景设置为红色的最佳方法,当值
【问题讨论】:
标签: wpf triggers styles textblock datatrigger
我正在尝试找出创建样式/触发器以将前景设置为红色的最佳方法,当值
【问题讨论】:
标签: wpf triggers styles textblock datatrigger
如果您不使用 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
}
}
【讨论】:
Foreground="{Binding MyValue, Converter={StaticResource valueToBackground}}" /> 这应该是Foreground="{Binding MyValue, Converter={StaticResource valueToForeground}}" />
您的 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>
【讨论】:
TextBlock.DataContext 而不是 TextBlock.Text。然后编写一个通用(转换发送者)DataContextChanged 事件,该事件可应用于每个Textblock
对于 Amsakanna 的解决方案,我必须向 Property Setter 添加一个类名:
【讨论】: