Xamarin Forms 在 XAML 中访问 ViewModel 属性

Xamarin Forms Access ViewModel Property in XAML

如何在 XAML 中访问我的 ViewModel 的 属性?

我试图仅在 ListView 选择了项目时才启用按钮。所选项目是绑定到我的 ViewModel 中的 SelectedCar 的数据。现在,我想检查 SelectedCar 是否为空,如果是,则禁用按钮;否则启用它。

我试过这样的东西

<StackLayout Orientation="Vertical">   
    <ListView x:Name="lvwCars" ItemsSource="{Binding Cars}"
      SelectedItem="{Binding SelectedCar}">
     <ListView.ItemTemplate>
      <DataTemplate>
       <ViewCell>
        <StackLayout Orientation="Horizontal">
         <Label Text="{Binding PlateNumber}" />
         <Label Text="{Binding OwnerName}" />    
        </StackLayout>
       </ViewCell>
      </DataTemplate>
     </ListView.ItemTemplate>
    </ListView>
</StackLayout>

<StackLayout Orientation="Horizontal"> 
    <Button x:Name="btnBack" 
            Text="Back" 
            Command="{Binding BackClickCommand}"/>
    <Button x:Name="btnNext" 
            Text="Next" 
            IsEnabled="False"
            Command="{Binding ConfirmClickCommand}">
     <Button.Triggers>
      <DataTrigger TargetType="Button" 
       Binding="{Binding Source={x:Reference MyCarsViewModel}, Path=SelectedCarProperty}" Value="null">
       <Setter Property="IsEnabled" Value="False"/>
      </DataTrigger>
     </Button.Triggers>
    </Button>
</StackLayout>

您应该使用 converter(实现 IValueConverter 的 class),因为您有数据但需要绑定到另一种格式的 属性,您有一个对象可以有一个值(不同于 null)或为 null,因此,您需要实现这样的转换器:

public class ObjectToBoolConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value != null;
        }       

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

然后您可以在您的代码中使用该转换器:

<StackLayout Orientation="Horizontal"> 
<StackLayout.Resources>
  <conv:ObjectToBoolConverter x:Key="Null2bool" />
</StackLayout.Resources>    
<Button x:Name="btnBack" 
            Text="Back" 
            Command="{Binding BackClickCommand}"/>
    <Button x:Name="btnNext" 
            Text="Next" 
            IsEnabled="{Binding SelectedCar,Converter={StaticResource Null2bool}}"
            Command="{Binding ConfirmClickCommand}">
    </Button>
</StackLayout>

不要忘记导入转换器的命名空间以便在 XAML

中使用

在这个例子中,我使用了 conv: 作为别名,所以你需要把它放在页面声明的顶部:

xmlns:conv="clr-namespace:Your.Converter.Namespace;assembly=Your.Assembly.Name"

例如,如果您的项目是 CarsMobile,并且您有 CarsMobile, CarsMobile.Droid and CarsMobile.iOS, 并且您将转换器 class 放在名为 Converters 的文件夹中(CarsMobile\Converters\ObjectToBoolConverter) 所以你的 xmlns 应该是这样的:

xmlns:conv="clr-namespace:CarsMobile.Converters;assembly=CarsMobile"

Reference https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters