我在我的.NET MAUI应用程序中实现了自动完成功能,并且在我的视图模型中使用CommunityToolkit.Mvvm
代码生成器来处理可观察的属性。
我有以下代码,当GetSuggestions()
更改时,我尝试调用SearchText
方法。
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(GetSuggestions))]
string searchText;
[ObservableProperty]
bool showSuggestions;
ObservableCollection<string> Suggestions { get; } = new();
private async Task GetSuggestions()
{
if(string.IsNullOrEmpty(SearchText) || SearchText.Length < 3)
return;
var data = await _myApiService.GetSuggestions(SearchText.Trim());
if(data != null && data.Count > 0)
{
Suggestions.Clear();
foreach(var item in data)
Suggestions.Add(item);
ShowSuggestions = true;
}
}
这给了我以下错误:
NotifyCanExecuteChangedFor的目标必须是可访问的IRelayCommand属性,但是"GetSuggestions“在MyViewModel类型中没有匹配项。
我在这里做错什么了?
发布于 2022-11-19 07:00:15
只是意味着更多的是对@RMinato的回答的修正。
正如我的评论所言:“虽然这一切都很有帮助,但我需要做一些不同的事情,包括使用[RelayCommand]
和将OnPropChanged
方法中的方法调用为Task.Run(() => this.MyMethodAsync()).Wait();
”。
我的代码看起来是:
[QueryProperty(nameof(Course), nameof(Course))]
public partial class CourseDetailViewModel : BaseViewModel
{
private readonly CourseService courseService;
public CourseDetailViewModel(CourseService courseService)
{
this.courseService = courseService;
}
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(GetCourseDetailCommand))]
Course course;
partial void OnCourseChanged(Course value)
{
Task.Run(() => this.GetCourseDetailAsync()).Wait();
}
[RelayCommand]
public async Task GetCourseDetailAsync()
{
if (GetCourseDetailCommand.IsRunning) return;
try
{
IsBusy = true;
course = await courseService.GetCourseDetailAsync(course.Id);
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to get course detail. Error: {ex.Message}");
await Shell.Current.DisplayAlert("Error!",
$"Failed to get course detail: {ex.Message}", "OK");
throw;
}
finally
{
IsBusy = false;
}
}
}
https://stackoverflow.com/questions/72758013
复制相似问题