I need to call an async method ConnectToLibrary
once a book is selected, meaning once SelectedBook
property is set. I saw many solutions. But all of them require hacks or starting a task/thread from a setter. My question, what's wrong with using a mediator like Messenger
from Microsoft Toolkit.Mvvm?
I can just register a callback to ConnectToLibrary
with Messenger.Register<...BookSelectedMessage>(...ConnectToLibrary...)
and then call Messenger.Send(new BookSelectedMessage())
from the SelectedBook
's setter.
Is this the correct way to do this in MVVM?
public MyViewModel : ObservableRecipient
{
public ObservableCollection<BookInfo> Books { get; } = new();
private BookInfo _selectedBook;
public BookInfo SelectedBook
{
get => _selectedBook;
set => SetProperty(ref _selectedBook, value);
}
private async Task ConnectToLibrary(BookInfo info)
{
await START_SOME_ASYNC_METHOD();
}
}
Nothing. In either case any Exception
is swallowed. And since you are asking, what's wrong with starting a thread from a Setter
? It sounds to me like the requirements of your app require this anyway, no?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.