【发布时间】:2022-01-17 15:58:27
【问题描述】:
我正在尝试将属性绑定到视图模型。
我收到以下错误:
错误 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 HomePage 有它的 HomeVm 视图模型,页面的一部分(ChildTestView)应该绑定到
Tested提供的 ChildTestVm。 -
我对毛伊岛不是很了解,但 setter 不应该只是: set => SetValue(ViewModelProperty, value);然后在 childview 中,您必须将 BindingContext 绑定到 xaml 中的 ViewModelProperty?
-
@T.Schwarz
BindingContext = value的值为value,因此设置器同时设置 BindingContext 和 ViewModelProperty。