【问题标题】:Ternary Operator in Xaml in Xamarin formsXamarin 形式的 Xaml 中的三元运算符
【发布时间】:2017-11-22 15:30:03
【问题描述】:

我正在开发 Xamarin 表单应用程序。我想根据属性的条件设置 Grdiview 背景颜色。

我知道我可以在类文件中创建一个新属性,然后绑定到 xaml,但是有没有办法在 Xaml 本身中使用三元条件。

我的代码是

<Grid Margin="5,0,5,5" Padding="10"  BackgroundColor="White">

这个 Grid 绑定到 model ,它具有属性 IsRead(可为空的布尔值)。现在我想设置条件,当 IsRead 为真时,将背景颜色设置为灰色,否则设置为白色。

如何在 xaml 中做到这一点?

【问题讨论】:

    标签: xamarin.forms


    【解决方案1】:

    我从未听说过这样的事情,但您可以使用转换器。是您最好的选择。它干净、可重复使用且易于编程。

    这是针对这种需求的精心设计的解决方案(当然,您可以通过多种方式来解决,这只是其中一种)。

    创建一个结构以使解决方案完全可重用:

    public struct NullableBoolColorScheme
    {
        public Color TrueColor { get; set; }
        public Color FalseColor { get; set; }
        public Color NullColor { get; set; }
    
        public NullableBoolColorScheme(Color trueColor, Color falseColor, Color nullColor)
        {
            TrueColor = trueColor;
            FalseColor = falseColor;
            NullColor = nullColor;
        }
    
        public Color GetColor(bool? value)
        {
            if (!value.HasValue)
                return NullColor;
            else
                return value.Value ? TrueColor : FalseColor;
        }
    }
    

    创建您的转换器:

    public class NullableBoolToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is bool?)) return null;
    
            Color returningColor = Color.Default;
    
            if (parameter != null && parameter is NullableBoolColorScheme)
                returningColor = ((NullableBoolColorScheme)parameter).GetColor((value as bool?));
    
            return returningColor;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new Exception("Conversion not allowed");
        }
    }
    

    在您的 ViewModel 中处理它:

    public class MyViewModel // Remember to implement INotifyPropertyChanged and raise property changes
    {
        public bool? MyNullableBoolProperty
        {
            get;
            set; 
        }
    
        public NullableBoolColorScheme AppColorScheme { get; }
    
        public MyViewModel()
        {
            AppColorScheme = new NullableBoolColorScheme(Color.Gray, Color.White, Color.Transparent /* Some possibilities are open here =) */);
        }
    }
    

    在 XAML 中使用它:

    <!-- Declare your namespace -->
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:converter="clr-namespace:Namespace.Converters"
             ...
             >
    <!-- Create your resources dictionary and add a converter instance -->
        <ContentPage.Resources>
            <ResourceDictionary>
                <converter:NullableBoolToColorConverter x:Key="NullableBoolToColorConverter" />
            </ResourceDictionary>
        </ContentPage.Resources>
        <!-- Have fun -->
        <Grid Margin="5,0,5,5" 
              Padding="10"  
              BackgroundColor="{Binding MyNullableBoolProperty, Mode=OneWay, Converter={StaticResource NullableBoolToColorConverter}, ConverteParameter={Binding AppColorScheme}}">
            ...
        </Grid>
        ...
    </ContentPage>
    

    希望对你有帮助。

    【讨论】:

    • ConverterParameter 绑定不起作用。但要做到这一点,我已经声明了一个资源: Black# bfbfbfTransparent 并将其链接到 ConverterParameter : {Binding myProperty, Mode=OneWay, Converter={StaticResource NullableBoolToColorConverter}, ConverterParameter={StaticResource颜色边框值}}
    【解决方案2】:

    您不能在 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}">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2016-09-13
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2020-01-10
      相关资源
      最近更新 更多