从winform打开wpf抛出对象引用未设置为的实例

时间:2016-06-21 04:25:37

标签: c# .net wpf winforms

我有一个WPF自定义控件,我需要从WinForm打开它。我已按照http://weblogs.asp.net/jdanforth/open-a-wpf-window-from-winformsOpen WPF window in WindowsForm APP

中提到的所有步骤进行操作

但它仍然为我提供了一个未设置为异常实例的对象引用。

Winform的:

private void button1_Click(object sender, EventArgs e)
        {
            var notificatioinapp = new WpfCustomControlLibrary1.Window1();
            ElementHost.EnableModelessKeyboardInterop(notificatioinapp);
            notificatioinapp.Show();
        }

WPF自定义控件:

public partial class Window1 : Window
    {
        public Window1() : base()
        {
            InitializeComponent();
            this.Closed += this.NotificationWindowClosed;
        }
    public new void Show()
    {
        this.Topmost = true;
        base.Show();

        this.Owner = System.Windows.Application.Current.MainWindow;
        this.Closed += this.NotificationWindowClosed;
        var workingArea = Screen.PrimaryScreen.WorkingArea;

        this.Left = workingArea.Right - this.ActualWidth;
        double top = workingArea.Bottom - this.ActualHeight;

        foreach (Window window in System.Windows.Application.Current.Windows)
        {
            string windowName = window.GetType().Name;

            if (windowName.Equals("NotificationWindow") && window != this)
            {
                window.Topmost = true;
                top = window.Top - window.ActualHeight;
            }
        }

        this.Top = top;
    }
    private void ImageMouseUp(object sender,
        System.Windows.Input.MouseButtonEventArgs e)
    {
        this.Close();
    }

    private void DoubleAnimationCompleted(object sender, EventArgs e)
    {
        if (!this.IsMouseOver)
        {
            this.Close();
        }
    }

    private void NotificationWindowClosed(object sender, EventArgs e)
    {
        foreach (Window window in System.Windows.Application.Current.Windows)
        {
            string windowName = window.GetType().Name;

            if (windowName.Equals("NotificationWindow") && window != this)
            {
                // Adjust any windows that were above this one to drop down
                if (window.Top < this.Top)
                {
                    window.Top = window.Top + this.ActualHeight;
                }
            }
        }
    }
}

感谢任何支持。

1 个答案:

答案 0 :(得分:4)

Application.Current 实际上是针对WPF应用程序的。所以我认为既然你试图从WinForms应用程序打开WPF应用程序,你需要在访问它之前首先初始化WPF应用程序的实例。

if ( null == System.Windows.Application.Current )
{
   new System.Windows.Application();
}

如果这不起作用,请尝试在WPF窗口的已加载事件中设置Application.Current.MainWindow = this;

这应该做好修复。

编辑:

private void button1_Click(object sender, EventArgs e)
{

    if (null == System.Windows.Application.Current)
    {
        new System.Windows.Application();
    }

    var wpfwindow = new Window();
    wpfwindow = new WpfCustomControlLibrary1.Window1();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Show();

}