如何在XAML中使用条件打印textBlock

本文关键字:条件 打印 textBlock XAML | 更新日期: 2023-09-27 18:05:31

如果数字小于80,则需要在textBlock repeat中打印并将颜色涂为红色,如果数字大于或等于80,则打印成功并将颜色涂为绿色。

我如何在XAML中做到这一点?

如何在XAML中使用条件打印textBlock

转换器。

遗憾的是没有不相等触发器之类的,所以应该使用转换器。

<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();
    }
}
<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
}

另一个转换器看起来类似于笔刷转换器,但返回"成功"或"重复"。