c# - 如何在 XAML 中使用条件打印文本 block ?

标签 c# wpf xaml

如果数字小于 80,我需要在文本 block 中重复打印,并将颜色涂成红色,大于或等于 80,则使用绿色打印成功。

如何在 XAML 中执行此操作?

最佳答案

Converters .

遗憾的是,没有不等式触发器或类似的东西,所以使用转换器应该可以。

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

关于c# - 如何在 XAML 中使用条件打印文本 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7044828/

相关文章:

C#:如何在虚拟模式下有效地过滤(隐藏)ListView 项目?

c# - App.xaml 对象引用未设置为对象的实例

c# - 绑定(bind)到 ViewModel 的子类属性

c# - 我需要帮助翻译这部分 ECMAScript 语法吗?

c# - HttpClient的多种实现

.net - WPF ListBox VirtualizingStackPanel.VirtualizationMode ="Recycling"导致相同的列表项始终出现

c# - WPF:如何更改 TransitioningContentControl 背景颜色?

c# - 我如何按下控制

c# - 重定向default.aspx

c# - XAML 中的映射命名空间不起作用