简体   繁体   English

我在 UserControl 中有一个按钮,它应该在主窗口中调用一个方法

[英]I Have a Button in a UserControl which should call a method in the main window

i would like to trigger a method in the main Windows through a Button in a user Controll (my sidebar).我想通过用户控件(我的侧边栏)中的按钮触发主 Windows 中的方法。 How can i do this?我怎样才能做到这一点?

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如果这不起作用,您可以做的是将 Window.GetWindow(this) 的结果转换为 MainWindow,如下所示

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.您也可以使用与此处显示的不同的事件处理程序来满足您的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM