从用户控件 WPF 调用主窗口中的公共函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25302838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call public function in Main Window from a User Control WPF
提问by Orionlk
I have a Main Window which includes some User Controls that are initialized in the WPF XAML
MainWindow.xaml.
我有一个主窗口,其中包含一些在 WPF XAML
MainWindow.xaml中初始化的用户控件。
<Grid>
<local:RegularUnit x:Name="ucRegularUnit" Grid.Row="0" />
<local:Actions x:Name="ucActions" Grid.Row="1" />
// .....
</Grid>
I have a public function in the Main Window which I want to call after clicking a Button in my User Control. After searching for some solutions, I found a way to get the parent window instance in my User Control class, but it can't find the function when I'm using parentWindow.myFunction().
我在主窗口中有一个公共函数,我想在单击用户控件中的按钮后调用它。在搜索了一些解决方案后,我找到了一种在我的用户控件类中获取父窗口实例的方法,但是在我使用parentWindow.myFunction().
User Control RegularUnit.cs:
用户控制RegularUnit.cs:
public partial class RegularUnit : UserControl
{
public RegularUnit()
{
InitializeComponent();
}
private void Button_SearchSerialNumber_Click(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
//parentWindow. //Can't find the function myFunction()
}
}
MainWindow.cs:
MainWindow.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void myFunction()
{
// Do Some Stuff...
}
}
What am I doing wrong, and how can I fix it?
我做错了什么,我该如何解决?
回答by Dirk
You can't call myFunctionon parentWindowbecause it's not a member of the standard WPF Windowclass but of your custom MainWindow.
您无法调用myFunction,parentWindow因为它不是标准 WPFWindow类的成员,而是您自定义的MainWindow.
What you could do is to cast the result of Window.GetWindow(this)to MainWindow, like
您可以做的是将结果转换为Window.GetWindow(this)to MainWindow,例如
MainWindow parentWindow = (MainWindow) Window.GetWindow(this);
parentWindow.myFunction();
However this is a really bad class design because now your user control depends on being embedded in a specific window.
然而,这是一个非常糟糕的类设计,因为现在您的用户控件取决于嵌入到特定窗口中。
What you should rather do is to add an event to the user control on which the parent control can subscribe to.
您应该做的是向父控件可以订阅的用户控件添加一个事件。
public event EventHandler SerialNumberSearch;
private void Button_SearchSerialNumber_Click(object sender, RoutedEventArgs e)
{
var handler = SerialNumberSearch;
if (handler != null) handler(this, EventArgs.Empty);
}
Of course you could use a different kind of EventHandler, depending on what you need.
当然,您可以使用不同类型的 EventHandler,具体取决于您的需要。
回答by Ketan Dubey
System.Windows.Application.Current.Windows.OfType<YourWindow>().SingleOrDefault(x => x.IsActive).YourPublicMethod();
Although the above code is a messy way of doing it, but it gets the job done nevertheless.
虽然上面的代码是一种凌乱的方式,但它仍然完成了工作。

