如何在Wpf中的Usercontrol中调用MahApps Metro对话框

时间:2015-11-27 05:50:25

标签: wpf wpf-controls mahapps.metro

当我尝试拨打MahApps Metro对话框时,我在传递值时遇到错误

在传递参数时调用Dialog Control我需要传递Metrowindow参数

但我需要在用户控件中调用它

以下是我需要Dialog控件时调用的方法

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

5 个答案:

答案 0 :(得分:4)

ShowMessageAsync是MetroWindow的扩展方法,因此该代码应该有效:

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

答案 1 :(得分:0)

让我根据Rajesh的答案给你一个reallife例子。

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

答案 2 :(得分:0)

@Rajesh代码在usercontrol中为我做了null异常。即使我的MainWindow是MetroWindow类。但是,以下工作适用于我的配置;

        #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

答案 3 :(得分:0)

这是另一种选择,因为我尝试使用Rajesh Akshith的答案,但这对我不起作用。

在usercontrol中,

using MahApps.Metro.Controls.Dialogs;

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

我是来自Mahapps Dialog的引用。我认为这更有用,它也可以在辅助类中编写,你可以从任何地方调用它。

答案 4 :(得分:0)

在我的MainWindow中:

dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile 'org.mockito:mockito-core:2.+'
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.0'
testCompile group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.0'
implementation("com.google.guava:guava:29.0-jre")
compile group: 'net.sf.trove4j', name: 'trove4j', version: '3.0.3'
}

在我的UserControl中:

public async void ShowMessagesDialog(string title, string message)
    {
        logger.Add("ShowMessagesDialog: " + message);
        var messageDialogSettings = new MetroDialogSettings
        {
            AffirmativeButtonText = "Aceptar",
            OwnerCanCloseWithDialog = false,
            ColorScheme = this.MetroDialogOptions.ColorScheme,
        };
        await this.ShowMessageAsync(title, message, MessageDialogStyle.Affirmative, messageDialogSettings);
    }