【问题标题】:UWP Color Foreground ListView ConditionUWP 颜色前景 ListView 条件
【发布时间】:2016-05-09 15:39:30
【问题描述】:

我想知道是否可以在 ListView 中的文本块上设置条件。我解释一下:

我有一个包含一些数据的模型,并且这个模型中有一个“数量”。如果金额为负数,我想将前景设为红色,如果金额为正数,我希望将前景设为绿色。

 <TextBlock RelativePanel.AlignRightWithPanel="True"
                               Foreground="Red"
                               FontWeight="Bold">
                        <Run Text="{Binding Amount}" />
                        <Run Text="€" />
 </TextBlock>

这是文本块,他在 ListView.ItemTemplate 中。

问候,

安东尼

【问题讨论】:

    标签: listview colors uwp textblock foreground


    【解决方案1】:

    您应该使用转换器。创建一个派生自IValueConverter 的类(例如AmountColorConverter)。

    public object Convert(object value, ...)
    {
        var val = (double)value;
        return val >= 0
            ? Colors.Green
            : Colors.Red;
    }
    

    实现后,在 XAML 中创建转换器实例并在绑定中引用它:

    <converter:AmountColorConverter x:Key="AmountColorConverter"/>
    <TextBlock RelativePanel.AlignRightWithPanel="True"
               Foreground="{Binding Amount, Converter={StaticResource AmountColorConverter}}"
               FontWeight="Bold">
        <Run Text="{Binding Amount}" />
        <Run Text="€" />
    </TextBlock>
    

    【讨论】:

    • 非常感谢您的回复,我做到了,但没有改变前景的颜色。我尝试调试,返回的颜色还可以,但没有改变颜色……太奇怪了
    • @AnthonyNfr Run 类也有一个 Foreground 属性。也许转换器应用于TextBlock 的值会被Run 实例的值覆盖。
    【解决方案2】:

    我已经尝试过了。 他是我的 xaml 代码:

    <TextBlock HorizontalAlignment="Right"
               Grid.Column="2"
               Grid.Row="0"
               Foreground="{Binding Amount, Mode=TwoWay, Converter={StaticResource ForegroundColorAmount}}"
               FontWeight="Medium">
                   <Run Text="{Binding Amount}" Foreground="{Binding Amount, Mode=TwoWay, Converter={StaticResource ForegroundColorAmount}}" />
                   <Run Text="€" />
    

    当然我使用了 using :

    xmlns:converters="using:Sample.Converters"
    

    这里是我的转换器类:

        public class ForegroundColorAmount : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var val = (double)value;
            if (val >= 0)
            {
                return Colors.Green;
            }
            else
            {
                return Colors.Red;
            }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    

    谢谢。

    安东尼

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-12
      • 2020-06-27
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多