您不能在 XAML 中使用三元。
解决方案 1(使用转换器):
您或许可以使用ValueConverter。创建一个实现IValueConverter的转换器。
public class ReadUnReadToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool? isRead = Convert.ToBoolean(value);
if(isRead.HasValue && isRead.Value == true)
{
return Color.Grey;
}
return Color.White;
}
//You may not need the Convert Back method. This will need to convert Color back to Boolean
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在你的XAML Resource中,将这个类添加为静态资源,然后你就可以使用这个转换器来绑定值并基于这个进行转换。
<ContentPage.Resources>
<local:ReadUnReadToColorConverter x:Key="ReadUnReadToColorConverter" />
</ContentPage.Resources>
现在,按如下方式将此转换器绑定到您的网格:
<Grid Margin="5,0,5,5" Padding="10" BackgroundColor="{Binding IsRead, Converter={StaticResource ReadUnReadToColorConverter}}">
解决方案 2(使用属性绑定(仅限 OneWay 解决方案)):
您可以简单地在您的ViewModel 中拥有一个Color 属性,并根据以下条件在该属性的get 方法中返回值:
public Color ReadUnReadBackgroundColor
{
get
{
if(IsRead.HasValue && IsRead.Value == true)
{
return Color.Grey;
}
return Color.White;
}
}
现在将其与 Grid 的 BackgroundColor 属性绑定:
<Grid Margin="5,0,5,5" Padding="10" BackgroundColor="{Binding ReadUnReadBackgroundColor}">