[英]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.