Hello devz,
It happens sometimes with WPF that a popup or a MessageBox is hidden and can block the whole application.
To avoid this, just do the following:
var msgBoxResult = MessageBox.Show(Application.Current.MainWindow, "Are you sure?", "Delete item", MessageBoxButton.YesNo, MessageBoxImage.Question);
The Application.Current.MainWindow is the solution…
But please pay attention that this parameter can be different! Indeed it’s an implementation of IWin32Window that will own the modal dialog box. So it will not be always Application.Current.MainWindow…
For more info please look at the MSDN post: here.
UPDATE:
But actually even in this case, we could have issues…
This is the correct way of doing it.
I created a MessageBoxWrapper that can manage the UI Dispatcher:
using System; using System.Windows; using System.Windows.Threading; namespace MessageBoxTest { public class MessageBoxWrapper { public static MessageBoxResult Show(string msg, string title, MessageBoxButton buttonStyle, MessageBoxImage image) { var result = MessageBoxResult.None; if (Application.Current.Dispatcher.CheckAccess()) result = MessageBox.Show(Application.Current.MainWindow, msg, title, buttonStyle, image); else Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { result = MessageBox.Show(Application.Current.MainWindow, msg, title, buttonStyle, image); })); return result; } } }
Usage:
var msg = "This is the message!"; var title = "This is the title"; MessageBoxWrapper.Show(msg, title, MessageBoxButton.OK, MessageBoxImage.Warning);
Happy coding! 🙂