2017-08-02 31 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 ""; 
相關問題