Picker的动态ItemDisplayBinding

问题描述 投票:2回答:2

Picker具有ItemDisplayBinding属性,可以使用此"{Binding PropertyA}"语法设置要显示的Itemsource属性名称。但我有UI条件与更改属性名称有关,以动态显示。我有这样的房产。

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

我该怎么办如果我想要这个属性绑定而不是"{Binding PropertyA}"

xamarin xamarin.forms
2个回答
1
投票

如果ID属于ItemDisplayBinding属性之一。请按如下所示。

在其中创建一个PropertyDisplay属性,这可用于显示Property或PropertyB,是否为其他Property。

属性类:包含属性,属性等。

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

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

最终效果:

enter image description here


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}}"/>

最后,每个选择器的项目将在显示之前进入此转换器。所以你可以选择你想要在那里展示的东西。

© www.soinside.com 2019 - 2024. All rights reserved.