Event handling in different views in WPF
Hello. So I have a button in my main window, And i would like for it to change controls in a different window. How would i link the event handler of the button of the mainwindow to the secondary window. I know you're supposed to use a view model for that, but i am unsure of how to implement it
9 Replies
This is, as far as I'm aware, done via messaging.
My suggestion is to use community toolkit (I'll.refer to it as CT for shot) MVVM. It has the necessary tools for implementing a Viewmodel and massaging.
You'd create a Viewmodel for your main window. Within it define a command.
Using CT such a Viewmodel would look like this
The special sauce is the
partial
and the [RelayCommand] attribute. Behind the scenes this generates additional C# code that contains a property called ButtonPressedCommand
.
In your view, MainWindow.xaml
, you'd specify the datacontext to be the Viewmodel class we've just definedStack Overflow
How do I set a ViewModel on a window in XAML using DataContext prop...
The question pretty much says it all.
I have a window, and have tried to set the DataContext using the full namespace to the ViewModel, but I seem to be doing something wrong.
<Window x:Class="
Finally you can bind the button press to the command in your Viewmodel
Now, an important question for you regarding the second window: will there be only one instance of it running at a time, or multiple?
If multiple, based on what do you determine which one of the windows should be affected by the button press?
Here is the documentation for CT messaging
https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/messenger
Messenger - Community Toolkits for .NET
A type that can be used to exchange messages between different objects
I will try to implement this. Thank you
@Denis I am actually lost
I already have my main view model inherit from observable object
Alright, where exactly are you stuck?
I've suggested inheriting from
ObservableRecipient
, because that is a requirement for messaging
Please provide as many $details as possibleWhen you ask a question, make sure you include as much detail as possible. Such as code, the issue you are facing, and what you expect the result to be. Upload code here https://paste.mod.gg/ (see $code for more information on how to paste your code)
$codegif