我的WPF应用程序中有一个MainWindow和一个user-control。我想在没有MainWindow的情况下调用user-control中的creating new instance of MainWindow函数。为此,我制作了用户控件的主窗口父级。我在下面编写了这段代码,用于调用父函数。
子用户控制
public partial class AppLogo : UserControl
{
public MainWindow myparent { get; set; }
private void activate_Click_1(object sender, RoutedEventArgs e)
{
myparent.function();
}
. . .
}父窗口:
public MainWindow()
{
InitializeComponent();
AppLogo childWindow = new AppLogo();
. . .问题:
Window作为user-control的父级Yes,那么为什么Object Reference is Null会产生错误。No it is not possible,那么我如何才能实现这个目标。,因为根据需要在我的应用程序中创建用户控件是必要的.。发布于 2013-09-15 16:13:39
如果希望在UserControl中引用MainWindow,请使用以下代码:
MainWindow mw = Application.Current.MainWindow as MainWindow;http://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow.aspx
private void activate_Click_1(object sender, RoutedEventArgs e)
{
MainWindow mw = Application.Current.MainWindow as MainWindow;
if(mw != null)
{
mw.function();
}
}第二种解决办法:
在代码中,应该在myparent构造函数中设置MainWindow属性:
public MainWindow()
{
InitializeComponent();
AppLogo childWindow = new AppLogo();
childWindow.myparent = this;
...
}在activate_Click_1事件处理程序中,好习惯是检查myparent是否为null:
private void activate_Click_1(object sender, RoutedEventArgs e)
{
if(myparent != null)
myparent.function();
else
...
}发布于 2013-09-15 16:10:43
我假设空引用用于AppLogo上的AppLogo属性
在这行AppLogo childWindow = new AppLogo();后面添加一条childWindow.myparent = this;
发布于 2013-09-15 16:10:57
您可以按照建议引入子父依赖关系,但是,由于您没有实例化MainWindow,所以在调用myparent.function()时,您应该期望得到一个空引用异常;
首先,您需要实例化MainWindow,然后通过调用AppLogo .set_myparent来设置子父关系,只有这样,您的调用才不会失败。
https://stackoverflow.com/questions/18814474
复制相似问题