如何将属性绑定到 MAUI 中的视图模型?

sin*_*rix 5 c# xaml xamarin maui

我正在尝试将属性绑定到视图模型。

我收到以下错误:

错误 XFC0009 找不到“ViewModel”的属性、BindableProperty 或事件,或者值和属性之间的类型不匹配。

public abstract class BaseTestView : ContentView
{
    public BaseVm ViewModel
    {
        get => (BaseVm)GetValue(ViewModelProperty);
        set => SetValue(ViewModelProperty, BindingContext = value);
    }
    public static BindableProperty ViewModelProperty { get; set; } = BindableProperty.Create(nameof(ViewModel), typeof(BaseVm), typeof(BaseTestView));
}
Run Code Online (Sandbox Code Playgroud)
public abstract class BaseTestView : ContentView
{
    public BaseVm ViewModel
    {
        get => (BaseVm)GetValue(ViewModelProperty);
        set => SetValue(ViewModelProperty, BindingContext = value);
    }
    public static BindableProperty ViewModelProperty { get; set; } = BindableProperty.Create(nameof(ViewModel), typeof(BaseVm), typeof(BaseTestView));
}
Run Code Online (Sandbox Code Playgroud)
<v:BaseTestView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:vm="clr-namespace:MyProject.ViewModels"
    xmlns:v="clr-namespace:MyProject.Views"
    x:Class="MyProject.Views.ChildTestView"
    x:DataType="vm:ChildTestVm">
    <v:BaseTestView.Content>
      <StackLayout>
          <Label Text="{Binding Foo}" />
      </StackLayout>
  </v:BaseTestView.Content>
</v:BaseTestView>




public partial class ChildTestView : BaseTestView
{
    public ChildTestView() : base()
    {
        InitializeComponent();
    }
}

public class ChildTestVm : BaseVm
{
    public string Foo { get; set; }

    public ChildTestVm()
    {
        Title = "Test";
        Foo = "some stuff";
    }
}

public class HomeVm : BaseVm
{ 
    public ChildTestVm Tested { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

知道这个错误意味着什么以及如何修复它吗?

Too*_*eve 2

我尝试了一些实验,但未能弄清楚为什么它给出了这个抱怨 - 我尝试的每个变体也给出了这个错误。


相反,这样做:

首先,设置BindingContextChildTestView的:

<v:ChildTestView BindingContext="{Binding Tested}" />
Run Code Online (Sandbox Code Playgroud)

该数据将 ChildTestView 绑定到 Tested 中的 ChildTestVm。

如果您还需要访问虚拟机以获取后台代码,请按以下方式操作:

ChildTestView.xaml.cs:

private ChildTestVm ViewModel => (ChildTestVm)BindingContext;
Run Code Online (Sandbox Code Playgroud)

现在在 ChildTestView 的方法中,您可以使用ViewModel.Foo.


注意:如果您动态更改Tested

如果您的代码在Tested = ...HomePage 加载并可见之后执行此操作,则需要Testedsetter 来执行此操作OnPropertyChanged();(或其他 MVVM 数据绑定机制)。这是通知 XAML 更改所必需的。