UWP颜色前景ListView条件

3
我想知道在ListView中是否有可能对文本块进行条件设置。我解释一下:
我的模型包含一些数据,其中包括“金额”。如果金额为负数,我希望将前景色设置为红色;如果金额为正数,我希望将前景色设置为绿色。
 <TextBlock RelativePanel.AlignRightWithPanel="True"
                               Foreground="Red"
                               FontWeight="Bold">
                        <Run Text="{Binding Amount}" />
                        <Run Text="€" />
 </TextBlock>

这是一个文本块,它位于ListView.ItemTemplate中。

祝好,

安东尼

2个回答

2
你应该使用一个转换器。创建一个类(例如AmountColorConverter),它派生自IValueConverter
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>

非常感谢您的回复,我已经尝试了,但前景颜色没有改变。我在调试中尝试了一下,颜色返回值是正确的,但是颜色没有改变...真奇怪。 - Anthony Nfr
@AnthonyNfr Run类也有一个Foreground属性。也许转换器应用于TextBlock的值会被Run实例的值覆盖。 - Herdo

0

我已经尝试过了。 这是我的 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();
    }
}

Thank's.

Anthony


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接