C
C#9mo ago
Kingdawanage

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
Denis
Denis9mo ago
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
public partial class MainWindowViewModel
: ObservableRecipient
{
[RelayCommand]
private void ButtonPressed()
{
// Todo: affect other window
}
}
public partial class MainWindowViewModel
: ObservableRecipient
{
[RelayCommand]
private void ButtonPressed()
{
// Todo: affect other window
}
}
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 defined
Denis
Denis9mo ago
Stack 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="
Denis
Denis9mo ago
Finally you can bind the button press to the command in your Viewmodel
<Button Command="{Binding ButtonPressedCommand}" Content="Press me"/>
<Button Command="{Binding ButtonPressedCommand}" Content="Press me"/>
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?
Denis
Denis9mo ago
Messenger - Community Toolkits for .NET
A type that can be used to exchange messages between different objects
Kingdawanage
KingdawanageOP9mo ago
I will try to implement this. Thank you @Denis I am actually lost I already have my main view model inherit from observable object
Denis
Denis9mo ago
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 possible
MODiX
MODiX9mo ago
When 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)
Denis
Denis9mo ago
$codegif
Want results from more Discord servers?
Add your server