'Call a function when button is clicked in a different window (WPF app)
I launch a window from a page of my wpf app and I would like to call a function when a button is pressed in the child window
Here is the page that calls the window :
namespace AppWpf10
{
public partial class Prepare : System.Windows.Controls.Page
{
private void button_Click(object sender, RoutedEventArgs e)
{
Choice win2 = new Choice();
win2.Show();
}
public void DoStuff()
{
//CODE THAT DOES STUFF
}
}
}
The window launched :
namespace appWpf10
{
public partial class Choice : Window
{
private void button1_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
So I would like DoStuff()
to be called upon button1
being pressed in the other window. How should I do it ? By calling DoStuff()
in button1_Click
from the child window ? Or by adding an event "button1 pressed in the other window" ?
Either way, anyone knows how to write it ? Thanks in advance !
Solution 1:[1]
Well, there are many ways and by the looks of it, you're not going the MVVM route, which is fine. So, in your particular situation, a simple way is to subscribe to the child's button click event when you actually create the child, given that you named the button:
namespace AppWpf10
{
public partial class Prepare : System.Windows.Controls.Page
{
private void button_Click(object sender, RoutedEventArgs e)
{
Choice win2 = new Choice();
win2.Show();
win2.button1.Click += clickEventHandler;
}
private void clickEventHandler(object sender, RoutedEventArgs e)
{
DoStuff();
}
public void DoStuff()
{
//
}
}
}
Solution 2:[2]
One solution is to give parent to child window in constructor and then it can call its parent methods:
private void button_Click(object sender, RoutedEventArgs e)
{
Choice win2 = new Choice(this);
win2.Show();
}
public partial class Choice : Window
{
Prepare parent;
public Choice(Prepare parent)
{
this.parent = parent;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
parent.DoStuff();
this.Close();
}
}
Solution 3:[3]
Below code works for me. I have generated event for show popup which popup control is putting in another (MainWindow) window page and I am rendering from FooterPanel which is my UserControl in WPF.
foreach (Window window in Application.Current.Windows)
{
if (window.GetType() == typeof(MainWindow))
{
(window as MainWindow).MyPopup.IsOpen = true;
}
}
You can also refer the link which has another way to doing it. https://docs.microsoft.com/en-us/dotnet/desktop/wpf/events/how-to-add-an-event-handler-using-code?view=netdesktop-6.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Martin Heralecký |
Solution 3 | Khushbu kadia |