Xamarin将父BindingContext值转换为转换器

时间:2017-08-02 14:51:35

标签: xaml xamarin xamarin.forms

我有可选择汽车的主列表,以及包含所选汽车ID的第二个列表。

public class SelectCarsViewModel : BindableBase 
{
    public IList<Car> Cars = new List<Car>();
    public IList<string> SelectedCars = new List<string>();
}

public class Car
{
    public string Id {get; set;}
}

我需要在每辆选定的车旁边显示一个复选标记。我试图通过开发一个获取当前汽车ID和SelectedCars列表的转换器来实现这一目标。我在从XAML传递SelectedCars列表时遇到了困难。我能够传递SelectCarsPage,但不能传递它的BindingContext或它的SelectedCars属性。

<ContentPage x:Name="SelectCarsPage">
    <ListView ItemsSource=Cars>
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Text="{Binding Id, Converter={StaticResource IsCarSelected}, ConverterParameter={Binding Source={x:Reference Name=SelectCarsPage}, Path=SelectedCars}}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

public class IsCarSelected : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //parameter is SelectCarsPage and not the SelectedCars list.

        //I'd eventually like to get the following to work
        var selectedCars = (List<string>)parameter;
        return selectedCars.Contains(value.ToString()) ? "√" : "";
    }
}

4 个答案:

答案 0 :(得分:0)

如何创建一个像Car这样继承Car类的新类

{{1}}

在视图模型中管理它,而不是创建2个不同的列表?

答案 1 :(得分:0)

我认为您可以简单地将“IsSelected”布尔属性添加到“Cars”模型中。设置为“true”或“false”属性......

然后你的ValueConverter应该像

if(value != null && value is bool){

    if(((bool)value) == true)
        return "√";
    else
        return "";
}
else
    return "";

答案 2 :(得分:0)

您可以这样使用

var source =(参数为Binding).Source为ListView; if(source == null)返回结果;

var itemSource = source.ItemsSource作为IList;

答案 3 :(得分:0)

with tf.device('/device:GPU:0'):
  #code here: tf data and model

当执行绑定引用/源时,您不会绑定到DataContext,而是绑定到控件本身。如果要从其DataContext(视图模型)访问属性,则必须这样设置路径:

<Label Text="{Binding Id, Converter={StaticResource IsCarSelected}, ConverterParameter={Binding Source={x:Reference Name=SelectCarsPage}, Path=SelectedCars}}"/>

这种绑定命中控件本身,因为它允许获取属性的值,例如高度,宽度,可见性等。如果需要其DataContext中的属性,请使用DataContext对象,然后定位所需的属性。

祝你好运!

相关问题