我正在嘗試將屬性系結到視圖模型。
我收到以下錯誤:
錯誤 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
{
}
知道這個錯誤意味著什么以及如何修復它嗎?
uj5u.com熱心網友回復:
我嘗試了一些實驗,但未能弄清楚為什么它會產生這種抱怨 - 我嘗試的每個變體也都會出現該錯誤。
相反,這樣做:
首先,設定BindingContextChildTestView的:
<v:ChildTestView BindingContext="{Binding Tested}" />
該資料將 ChildTestView 系結到來自 Tested 的 ChildTestVm。
如果您還需要訪問 Vm 以獲取隱藏代碼,請按以下方式操作:
ChildTestView.xaml.cs:
private ChildTestVm ViewModel => (ChildTestVm)BindingContext;
現在在 ChildTestView 的方法中,您可以使用ViewModel.Foo.
注意:如果您動態更改Tested:
如果您在Tested = ...HomePage 加載和可見之后的任何地方都有代碼,那么讓它作業需要Testedsetter 來做OnPropertyChanged();(或其他 MVVM 資料系結機制)。這是通知 XAML 更改所必需的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/384145.html
