我尝试将对象参数通过
ViewModel Books
传递给 ViewModel Book Detail
。我将两个视图模型定义为 ObservableObject
并使用 ViewModel Books 中的字典来传递参数,如下所示:
我希望
Title = this.Book.Name;
能够工作并获取值,但是 this. Book
甚至 Book
属性单独为 null,但我可以在详细信息 XAML 页面中获取其值。我需要在 DetailsViewModel 构造函数上使用它。我的问题是什么?
BooksViewModel.cs
[RelayCommand]
async Task GoToDestinationAsync(Book book)
{
await Shell.Current.GoToAsync($"{nameof(DetailsPage)}", true,
new Dictionary<string, object>
{
{"Book",book}
});
}
详细信息ViewModel.cs
[QueryProperty(nameof(Book), "Book")]
public partial class BookDetailsViewModel : BaseViewModel
{
[ObservableProperty]
Book book;
public BookDetailsViewModel()
{
Title = this.Book.Name;
}
}
详细信息页.xaml.cs
public partial class DetailsPage : ContentPage
{
public DetailsPage(MonkeyDetailsViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
}
}
AppShell.cs
public partial class AppShell : Shell
{
public AppShell()
{
InitializeComponent();
Routing.RegisterRoute(nameof(DetailsPage), typeof(DetailsPage));
}
}
MauiProgram.cs
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.Services.AddSingleton<BooksViewModel>();
builder.Services.AddTransient<BookDetailsViewModel>();
builder.Services.AddSingleton<MainPage>();
builder.Services.AddTransient<DetailsPage>();
return builder. Build();
}
}
正如 Jason 所说,构造函数首先运行,因此您无法获取 Book 属性。我假设您可能想要设置 Title 属性的初始值。但我认为你不必在构造函数中设置该值。您可以在 Setter 方法中设置值:
public Book Book
{
...
set
{
book = value;
Title = book.Name;
}
}
[ObservableProperty]
string title;
希望有帮助!