Reputation: 965
I have a WPF custom control and I needs to open it from WinForm. I have followed all steps mentioned in http://weblogs.asp.net/jdanforth/open-a-wpf-window-from-winforms and Open WPF window in WindowsForm APP
But still it gives me an object reference not set to an instance of exceptions.
Winform:
private void button1_Click(object sender, EventArgs e)
{
var notificatioinapp = new WpfCustomControlLibrary1.Window1();
ElementHost.EnableModelessKeyboardInterop(notificatioinapp);
notificatioinapp.Show();
}
WPF custom control:
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;
}
}
}
}
}
Appreciate any support.
Upvotes: 0
Views: 1391
Reputation: 4464
Application.Current is Specific for WPF Application actually. So I think since you are trying to open WPF application from WinForms Application you need to initialize instance of WPF Application first before accessing it.
if ( null == System.Windows.Application.Current )
{
new System.Windows.Application();
}
If this doesn't work try setting Application.Current.MainWindow = this;
in loaded event of WPF window.
This should do the fix.
EDIT :
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();
}
Upvotes: 4