How to call MahApps Metro Dialog box in Usercontrol in Wpf

╄→гoц情女王★ 提交于 2019-12-22 11:27:30

问题


When I tried to call MahApps Metro Dialog Boxes I am getting error while Passing Values

while calling Dialog Control when Passing parameters I need to pass Metrowindow parameter

But I need to call it in User control

Below is the Method I will call when I need Dialog control

public async void ShowMessageDialog(object sender, RoutedEventArgs e)
        {
            // This demo runs on .Net 4.0, but we're using the Microsoft.Bcl.Async package so we have async/await support
            // The package is only used by the demo and not a dependency of the library!
            var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "Hi",
                NegativeButtonText = "Go away!",
                FirstAuxiliaryButtonText = "Cancel",
               // ColorScheme = MetroDialogOptions.ColorScheme
            };

            MessageDialogResult result = await this.ShowMessageAsync("Hello!", "Welcome to the world of metro!",
                MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, mySettings);

            if (result != MessageDialogResult.FirstAuxiliary)
                await this.ShowMessageAsync("Result", "You said: " + (result == MessageDialogResult.Affirmative ? mySettings.AffirmativeButtonText : mySettings.NegativeButtonText +
                    Environment.NewLine + Environment.NewLine + "This dialog will follow the Use Accent setting."));
        }

public static Task<MessageDialogResult> ShowMessageAsync(this MetroWindow window, string title, string message, MessageDialogStyle style = MessageDialogStyle.Affirmative, MetroDialogSettings settings = null)
        {
            window.Dispatcher.VerifyAccess();
            return HandleOverlayOnShow(settings, window).ContinueWith(z =>
            {
                return (Task<MessageDialogResult>)window.Dispatcher.Invoke(new Func<Task<MessageDialogResult>>(() =>
                {
                    if (settings == null)
                    {
                        settings = window.MetroDialogOptions;
                    }

                    //create the dialog control
                    var dialog = new MessageDialog(window, settings)
                    {
                        Message = message,
                        Title = title,
                        ButtonStyle = style
                    };

                    SizeChangedEventHandler sizeHandler = SetupAndOpenDialog(window, dialog);
                    dialog.SizeChangedHandler = sizeHandler;

                    return dialog.WaitForLoadAsync().ContinueWith(x =>
                    {
                        if (DialogOpened != null)
                        {
                            window.Dispatcher.BeginInvoke(new Action(() => DialogOpened(window, new DialogStateChangedEventArgs())));
                        }

                        return dialog.WaitForButtonPressAsync().ContinueWith(y =>
                        {
                            //once a button as been clicked, begin removing the dialog.

                            dialog.OnClose();

                            if (DialogClosed != null)
                            {
                                window.Dispatcher.BeginInvoke(new Action(() => DialogClosed(window, new DialogStateChangedEventArgs())));
                            }

                            Task closingTask = (Task)window.Dispatcher.Invoke(new Func<Task>(() => dialog._WaitForCloseAsync()));
                            return closingTask.ContinueWith(a =>
                            {
                                return ((Task)window.Dispatcher.Invoke(new Func<Task>(() =>
                                {
                                    window.SizeChanged -= sizeHandler;

                                    window.RemoveDialog(dialog);

                                    return HandleOverlayOnHide(settings, window);
                                }))).ContinueWith(y3 => y).Unwrap();
                            });
                        }).Unwrap();
                    }).Unwrap().Unwrap();
                }));
            }).Unwrap();
        }

回答1:


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

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



回答2:


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();
             }));
        }



回答3:


@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



回答4:


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.



来源:https://stackoverflow.com/questions/33951004/how-to-call-mahapps-metro-dialog-box-in-usercontrol-in-wpf

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