在.net MAUI中使用CommunityToolkit.MVVM从ViewModel传递参数到ViewModel.&



我的接收视图模型(QuestionsPageViewModel)在通过Shell导航传递TopidId后没有接收它,如下面的代码所示。我在QuestionsPageViewModel中的LoadQuestions方法中放置了断点。当它被调用时,TopicId为空。我错过了什么?

HomePageViewModel

//This is in a command executed after clicking a button. And this is working fine
await Shell.Current.GoToAsync($"{nameof(QuestionsPage)}?TopicId={pack.TopicId}");

QuestionsPageViewModel

[INotifyPropertyChanged]
[QueryProperty(nameof(TopicId), nameof(TopicId))]
public partial class QuestionsPageViewModel
{
public ObservableRangeCollection<Question> QuestionsList { get; set; } = new();
[ObservableProperty]
string? title;
[ObservableProperty]
public string topicId;
public QuestionsPageViewModel()
{
LoadQuestions();
}
async void LoadQuestions()
{
Title = Utilities.ConvertTopicIdToString(short.Parse(TopicId));
try
{
using (var context = new DataContext())
{
QuestionPack questionPack = context.QuestionPacks
.First(x => x.TopicId == short.Parse(TopicId));
var questions = JsonConvert.DeserializeObject<List<Question>>(questionPack.Questions);
QuestionsList.AddRange(questions);
}
}
catch (Exception ex)
{
await Shell.Current.DisplayAlert("Error", $"Something went wrong: {ex}", "Cancel");
}
}
}
}

首先,您的字段topicId应该是私有的。CommumityToolkit。Mvvm将为您生成公共属性。

其次,topicIdnull,因为你在构造函数中调用的函数中检查它的值。在执行构造函数时,shell导航参数还没有初始化。

如果您想要确保topicId初始化后LoadQuestions()将被调用,请使用communitytoolkit。Mvvm自8.0.0版本以来应该生成一个局部方法,该方法可用于在ObservableProperty更改其值后执行一些代码。在你的例子中,这个方法的名字应该是OnTopicIdChanged(string value)

尝试在视图模型中添加此方法,并从构造函数中删除函数调用:

partial void OnTopicIdChanged(string value)
{
LoadQuestions();
}

最新更新