✅ WPF - how to correctly call a method in the ViewModel when an event occurs in the View?
I want to call a method in the ViewModel when an event happens in the View. That is, when the View is loaded, I want it to execute a Authentication method in the ViewModel:
I get
Error CS0407 'Task MainWindow.MyToolWindow_LoadedAsync(object, RoutedEventArgs)' has the wrong return type
at compile time.When coding MyToolWindow_LoadedAsync, I followed the intellisence warning about naming, uing void and not awaiting to end up with how it looks preently.
I know it's me - what am I doing wrong?6 Replies
Simple answer, a event handler has no return type. The method should look like this:
private async void MyToolWindow_LoadedAsync(object sender, RoutedEventArgs e)
But the right way with a viewmodel is the MVVM Pattern.
https://learn.microsoft.com/de-de/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-patternthanks for the reply. private async void gives the intellisense warning of
VSTHRD100 Avoid async void methods
Also, yeah I'm trying to get to grips with MVVM and have watched lots of videos. Putting it into practice is another issue! Should the right approach involve commands somehow? I know roughly how to tie viewmodel commands to button clicks etc, but can you just do the same for UiEvents?
If so, how do I do that, as UIElements have the Command
attribute, but UIEvents don't?gui event handlers are the exception where you can use async void
because you have no other option
you can also use behaviors to avoid having to manually call the method in the codebehind and just bind the event directly to a command
but this is fine too its not a big deal if youre not doing it often
also you should use an mvvm library like
CommunityToolkit.Mvvm
avoids a shit ton of boilerplateI will always take advice from someone who uses phrases such as "a shit ton"
Thanks, 👍
haha :)
$close
Use the /close command to mark a forum thread as answered