2017-08-02 96 views
1

我有一个可选汽车的主列表,第二个列表包含所选汽车的ID。Xamarin Pass Parent BindingContext转换器的值

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()) ? "√" : ""; 
    } 
} 

回答

0

如何创建一个从汽车类继承这样一个

public class CarWithSelectionInfo : Car 
    public bool Selected {get; set;} 
end class 

,并在您的视图模型对其进行管理,而不是创建2个不同的列表,一个新的类?

0

我想你可以简单地为你的“汽车”模型添加一个“IsSelected”布尔属性。设置为“真”或“假”的属性...

那么你ValueConverter应该是这样

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

    if(((bool)value) == true) 
     return "√"; 
    else 
     return ""; 
} 
else 
    return ""; 
相关问题