[英]UWP Color Foreground ListView Condition
I would like to know if it's possible to make a condition on a textblock in a ListView. 我想知道是否可以在ListView中的文本块上创建一个条件。 I explain :
我解释 :
I have a models which contains some data and there is an "amount" in this models. 我有一个包含一些数据的模型,这个模型中有一个“数量”。 If the amount is negative I would like to put the foreground in red, and if it's positive I would like to put the foreground in green.
如果金额是负数,我想把前景设为红色,如果是正数,我想将前景设为绿色。
<TextBlock RelativePanel.AlignRightWithPanel="True"
Foreground="Red"
FontWeight="Bold">
<Run Text="{Binding Amount}" />
<Run Text="€" />
</TextBlock>
This is the textblock, he is in a ListView.ItemTemplate. 这是文本块,他在ListView.ItemTemplate中。
Regards, 问候,
Anthony 安东尼
You should use a converter. 你应该使用转换器。 Create a class (eg
AmountColorConverter
) that derives from IValueConverter
. 创建一个派生自
IValueConverter
的类(例如AmountColorConverter
)。
public object Convert(object value, ...)
{
var val = (double)value;
return val >= 0
? Colors.Green
: Colors.Red;
}
Once implemented, create an instance of the converter in XAML and reference it in the binding: 实现后,在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>
I've already try it. 我已经尝试过了。 He my xaml code :
他是我的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="€" />
And of course I used the using : 当然我用的是:
xmlns:converters="using:Sample.Converters"
And here my converter class : 在这里我的转换器类:
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 安东尼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.