How to call MahApps Metro Dialog box in Usercontrol in Wpf

点点圈 提交于 2019-12-06 13:42:20

ShowMessageAsync is an extension method for MetroWindow, so this code should work:

var metroWindow = (Application.Current.MainWindow as MetroWindow); 
await metroWindow.ShowMessageAsync(title, message);

Let me give you a reallife example based on Rajesh answer.

 async void LoadData()
        {
            var metroWindow = (Application.Current.MainWindow as MetroWindow);
            var controller = await metroWindow.ShowProgressAsync("Procesando", "Obtener datos de la base de datos", 
                false, new MetroDialogSettings() { AnimateShow = true, ColorScheme = MetroDialogColorScheme.Theme});
            controller.SetIndeterminate();

            await viewModel.LoadData();

            await Dispatcher.BeginInvoke((Action)(async () =>
             {
                 DataGrid1.ItemsSource = viewModel.AModels;

                 await controller.CloseAsync();
             }));
        }

@Rajesh code does null exception for me inside usercontrol. Even though my MainWindow is a MetroWindow class. However, the below worked for my configuration;

        #region try show Message
        try
        {

            #region ok, lets show message
            foreach (System.Windows.Window window in System.Windows.Application.Current.Windows)
            {
                if (window.GetType() == typeof(MainWindow))
                {

                    var controller = await (window as MainWindow).ShowProgressAsync("My Title", "My long message content text.",
                    false, new MetroDialogSettings() { AnimateShow = true, ColorScheme = MetroDialogColorScheme.Theme });

                }
            }
            #endregion ok, lets show message

        }
        catch (Exception ex)
        {

            #region error block


            #endregion error block

        }
        #endregion try show Message

This is a another option because i was try with Rajesh Akshith answer but it is not work for me.

In usercontrol,

using MahApps.Metro.Controls.Dialogs;

private IDialogCoordinator dialogCoordinator;
public async Task ShowMessageAsync()
        {
            dialogCoordinator = DialogCoordinator.Instance;
            await dialogCoordinator.ShowMessageAsync(this,"Header","Body");
        }

I was reference from Mahapps Dialog .I think this was more useful and It also can write in helper class and you can call this from anywhere.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!