![](/img/trans.png)
[英]C# CommunityToolkit.Mvvm ObservableProperty on a list
[英]Call method when ObservableProperty changes using CommunityToolkit.Mvvm
我正在我的 .NET MAUI 應用程序中實現自動完成功能,並且在我的視圖 model 中使用CommunityToolkit.Mvvm
代碼生成器來處理可觀察的屬性。
我有以下代碼,我正在嘗試在SearchText
更改時調用GetSuggestions()
方法。
[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 中沒有匹配項。
我在這里做錯了什么?
我想這里有兩個問題。
發生這種情況是因為GetSuggestions
不是命令。 嘗試將[RelayCommand]
屬性添加到您的方法中。
[RelayCommand]
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
鏈接到自動生成的命令。
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(GetSuggestionsCommand))]
string searchText;
你需要
SearchText 更改時調用 GetSuggestions() 方法。
NotifyCanExecuteChangedFor
屬性不這樣做。
在自動生成的源代碼中,您應該找到一個名為OnSearchTextPropertyChanged
的空部分方法。 嘗試實施它。
partial void OnSearchTextPropertyChanged(string value)
{
GetSuggestions();
}
如果這是您要搜索的內容, GetSuggestions
不需要使用RelayCommand
屬性進行標記。
僅意味着對@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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.