简体   繁体   中英

Mahapps Metro Dialog without MetroWindow

I want to use the dialog's of mahapps.metro in my application. My window is a normal window .

public partial class MainWindow : Window

not a

MetroWindow

Inside my button method I wrote this:

var metroWindow = (Application.Current.MainWindow as MetroWindow);
await metroWindow.ShowMessageAsync("Foo", "Bar");

I've added an ThemeManager inside App.xaml.cs

protected override void OnStartup(StartupEventArgs e)
{
    Tuple<AppTheme, Accent> appStyle = ThemeManager.DetectAppStyle(Application.Current);

    ThemeManager.ChangeAppStyle(Application.Current,
                                ThemeManager.GetAccent("Green"),
                                ThemeManager.GetAppTheme("BaseDark")); // or appStyle.Item1
    base.OnStartup(e);
}

And inside App.xaml I added

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Cobalt.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

When I execute my programm, I get an

NullReferenceException

because metroWindow == null

How can I solve this problem?

My window is a normal window.

That's your problem. Since ShowMessageAsync is an extension method for the MetroWindow class, you must have a reference to a MetroWindow in order to be able to call it. This means that you must replace your normal window with a MetroWindow or use another dialog. The ShowMessageAsync method only works with a MetroWindow .

The following code tries to cast the MainWindow window of your application to a MetroWindow but the cast will always fail if the main window is indeed a normal window:

var metroWindow = (Application.Current.MainWindow as MetroWindow);

That's why you get a NullReferenceException .

How can I solve this problem?

You must use a MetroWindow. There are no other solutions I am afraid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM