繁体   English   中英

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

[英]How can I bind a property to a view model in MAUI?

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

我收到以下错误:

错误 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
{ 
}

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

我尝试了一些实验,但未能弄清楚为什么它会产生这种抱怨——我尝试的每一种变化也都会产生这种错误。


相反,这样做:

首先,设置 ChildTestView 的BindingContext

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

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

如果您还需要访问 Vm 以获取后面的代码,请这样做:

ChildTestView.xaml.cs:

private ChildTestVm ViewModel => (ChildTestVm)BindingContext;

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


注意:如果您动态更改Tested

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM