Dynamic ItemDisplayBinding for Picker

时间:2019-04-17 02:47:25

标签: xamarin xamarin.forms

The Picker has ItemDisplayBinding property to set Itemsource's property name to display by using this "{Binding PropertyA}" syntax. But I have UI conditions that relating with changing property name to display dynamically. I have a property like this.

public string GetPropertyToDisplay 
{
    If (ID == 1)
    {
        return "PropertyA";
    }
    else if (ID == 2)
    {
        return "PropertyB";
    }
}

What should I do If I want this property to be binding instead "{Binding PropertyA}" ?

2 个答案:

答案 0 :(得分:1)

如果ID属于ItemDisplayBinding的属性之一。请参阅下面的

在其中创建一个PropertyDisplay属性,该属性可用于显示属性是PropertyA还是PropertyB,或者是其他Property。

属性类:包含PropertyA,PropertyB等。

public class Property 
{
    public int ID { set; get; }
    public string Name { set; get; }
    public string PropertyA { set; get; }
    public string PropertyB { set; get; }

    private string propertyDisplay = "Property";

    public string PropertyDisplay
    {
        get
        {
            if (ID == 1)
            {
                return PropertyA;
            }
            else if (ID == 2)
            {
                return PropertyB;
            }else
            return propertyDisplay;
        }
    }
}

ViewModel类:ItemSource,按如下所示设置测试数据:

public List<Property> listProperty { set; get; }

public ViewModel()
{

    listProperty = new List<Property>();

    listProperty.Add(new Property
    {
        ID = 1,
        Name = "Alex1",
        PropertyA = "10",
        PropertyB = "Ejemplo"
    });
    listProperty.Add(new Property
    {
        ID = 2,
        Name = "Alex2",
        PropertyA = "20",
        PropertyB = "Ejemplo"
    });

}

Xaml :选择器

<Picker Title="select" TextColor="Aqua" ItemsSource="{Binding listProperty}" ItemDisplayBinding="{Binding PropertyDisplay}"/>

最终效果

enter image description here

答案 1 :(得分:0)

使用转换器进行计算。 首先,创建您自己的转换器:

public class PikcerDisplayConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Model model = value as Model;
        if(ID == 1)
        {
            return model.PropertyA;
        }           
        return model.PropertyB;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在您的xaml中使用此转换器:

<ContentPage.Resources>
    <ResourceDictionary>
        <local:PikcerDisplayConverter x:Key="PikcerDisplayConverter"/>
    </ResourceDictionary>
</ContentPage.Resources>

<Picker ItemsSource="{Binding ItemsSource}" ItemDisplayBinding="{Binding ., Converter={StaticResource PikcerDisplayConverter}}"/>

最后,每个选择器的项目将在显示之前进入此转换器。因此,您可以选择要在此处显示的内容。