我需要在textBlock中重复打印,如果数字小于80并且颜色为红色,并且大于或等于80,则使用绿色打印成功。
我怎样才能在XAML中做到这一点?
答案 0 :(得分:3)
可悲的是,没有不平等触发器等,所以使用转换器应该这样做。
<TextBlock>
<TextBlock.Foreground>
<Binding Path="TestDouble">
<Binding.Converter>
<vc:ThresholdConverter BelowValue="{x:Static Brushes.Red}"
AboveValue="{x:Static Brushes.Green}"
Threshold="80" />
</Binding.Converter>
</Binding>
</TextBlock.Foreground>
<TextBlock.Text>
<Binding Path="TestDouble">
<Binding.Converter>
<vc:ThresholdConverter BelowValue="Repeat"
AboveValue="Successful"
Threshold="80" />
</Binding.Converter>
</Binding>
</TextBlock.Text>
</TextBlock>
public class ThresholdConverter : IValueConverter
{
public double Threshold { get; set; }
public object AboveValue { get; set; }
public object BelowValue { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double input;
if (value is double)
{
input = (double)value;
}
else
{
var converter = new DoubleConverter();
input = (double)converter.ConvertFrom(value);
}
return input < Threshold ? BelowValue : AboveValue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
答案 1 :(得分:2)
<local:NumberToBrushConverter x:Key="numberToBrushConverter" />
<local:NumberToTextConverter x:Key="numberToTextConverter" />
<TextBlock Background="{Binding Number, Converter={StaticResource numberToBrushConverter}}"
Text="{Binding Number, Converter={StaticResource numberToTextConverter}"/>
class NumberToBrushConverter: IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int number = (int)value;
return number < 80 ? Brushes.Red : Brushes.Green;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
#endregion
}
另一个转换器看起来类似于画笔转换器,但返回“成功”或“重复”。