簡體   English   中英

如何使用 XAML 中的條件打印文本塊?

[英]How to print a textBlock using conditionals in XAML?

如果數字小於 80 並塗成紅色,我需要在 textBlock 中重復打印,而大於或等於 80 的數字則用綠色打印成功。

我怎么能在 XAML 中做到這一點?

轉換器

可悲的是,沒有不等式觸發器等,所以應該使用轉換器。

<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
}

另一個轉換器看起來類似於刷子轉換器,但返回“成功”或“重復”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM