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

5

我试图将一个属性绑定到一个视图模型。

我遇到了以下错误:

错误 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));
}

<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; }
}

<ContentPage 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.Pages.HomePage"
    x:DataType="HomeVm">
    <ContentPage.Content>
      <StackLayout>
          <v:ChildTestView ViewModel="{Binding Tested}" />
          <!--             ^ Error here               /-->
      </StackLayout>
  </ContentPage.Content>
</ContentPage>




public partial class HomePage : ContentPage
{ 
}

有什么想法,可以解释一下这个错误的含义以及如何修复它吗?


你想为整个视图还是特定的堆栈布局使用Bindable? - SheikMydeenMuthu
@SheikMydeenMuthu HomePage有它的HomeVm视图模型,页面的一部分(ChildTestView)应该绑定到由“Tested”提供的ChildTestVm。 - sinsedrix
我对Maui不是很了解,但setter应该只是:set => SetValue(ViewModelProperty, value); 然后在childview中,您必须将BindingContext绑定到xaml中的ViewModelProperty吗? - T.Schwarz
BindingContext = value 的值为 value,因此 setter 同时设置了 BindingContext 和 ViewModelProperty。 - sinsedrix
1个回答

2

我尝试了一些实验,但无法弄清楚为什么会出现这个投诉 - 我尝试的每个变化也都出现了这个错误。


相反,可以这样做:

首先,设置ChildTestView的BindingContext

<v:ChildTestView BindingContext="{Binding Tested}" />

该代码将ChildTestView与来自Tested的ChildTestVm进行数据绑定。

如果您还需要在代码后台访问Vm,请按以下方式操作:

ChildTestView.xaml.cs:

private ChildTestVm ViewModel => (ChildTestVm)BindingContext;

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


注意:如果您动态地更改Tested

如果您在HomePage加载并可见后的任何位置有代码执行Tested = ...,那么让它正常工作需要Tested的setter执行OnPropertyChanged();(或其他MVVM数据绑定机制)。这是必要的,以通知XAML进行更改。


好的,这是一个变通的方法,如果我找不到更好的方法,我会使用它。谢谢你的尝试。 - sinsedrix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接