【问题标题】:Xamarin Pass Parent BindingContext Value to ConverterXamarin 将父 BindingContext 值传递给转换器
【发布时间】:2018-01-09 21:01:35
【问题描述】:

我有一个可选择汽车的主列表,还有一个包含所选汽车 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()) ? "√" : "";
    }
}

【问题讨论】:

    标签: xaml xamarin xamarin.forms


    【解决方案1】:
    <Label Text="{Binding Id, Converter={StaticResource IsCarSelected}, ConverterParameter={Binding Source={x:Reference Name=SelectCarsPage}, Path=BindingContext.SelectedCars}}"/>
    

    当您执行绑定引用/源时,您不会绑定到 BindingContext,而是绑定到控件本身。如果你想从它的 BindingContext(视图模型)访问一个属性,你必须像这样设置路径:

    Path=BindingContext.SelectedCars
    

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

    祝你好运!

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

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

        那么你的 ValueConverter 应该是这样的

        if(value != null && value is bool){
        
            if(((bool)value) == true)
                return "√";
            else
                return "";
        }
        else
            return "";
        

        【讨论】:

          【解决方案4】:

          你可以这样使用

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

          var itemSource = source.ItemsSource as IList;

          【讨论】:

            猜你喜欢
            • 2022-01-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-08-07
            • 1970-01-01
            相关资源
            最近更新 更多