Home > Blockchain >  I Have a Button in a UserControl which should call a method in the main window
I Have a Button in a UserControl which should call a method in the main window

Time:10-21

i would like to trigger a method in the main Windows through a Button in a user Controll (my sidebar). How can i do this?

CodePudding user response:

You can achieve this by calling the following inside of your buttons void.

private void Button_Click(object sender, RoutedEventArgs e)
{
    Window parentWindow = Window.GetWindow(this);
    parentWindow.Foo() // Foo is your Functions name inside of the main window.
}

If that doesn't work you could do is to cast the result of Window.GetWindow(this) to MainWindow, as seen below

MainWindow parentWindow = (MainWindow)  Window.GetWindow(this);
parentWindow.Foo();

However it's a really bad class design as now your user control depends on being embedded in a specific window.

What you should do instead, is to add an event to the user control which the parent control can subscribe to.

public event EventHandler myEventHandler;

private void Button_Click(object sender, RoutedEventArgs e)
{
    var handler = myEventHandler;
    if (handler != null) handler(this, EventArgs.Empty);
}

You may aswell use a different event handler than what's present here to fit your needs.

  • Related