Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

c# - WPF MessageBox with MVVM pattern?

Say I want to display some validation error to the user. In the MVVM pattern, I could have a label that is bound to some property on my viewmodel. But what if I wanted to show a message box while strictly adhering to the MVVM pattern. What would my viewmodel bind to, and how would it trigger a message box to be created/displayed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have an interface IMessageBoxService as:

interface IMessageBoxService
{
    bool ShowMessage(string text, string caption, MessageType messageType);
}

Create a WPFMessageBoxService class:

using System.Windows;

class WPFMessageBoxService : IMessageBoxService
{
    bool ShowMessage(string text, string caption, MessageType messageType)
    {
        // TODO: Choose MessageBoxButton and MessageBoxImage based on MessageType received
        MessageBox.Show(text, caption, MessageBoxButton.OK, MessageBoxImage.Information);
    }
}

In your ViewModel accept IMessageBoxService as a constructor parameter and inject WPFMessageBoxService using DI/IoC.

In the ViewModel, use IMessageBoxService.ShowMessage to show the MessageBox.

ShowMessageCommand = new DelegateCommand (
    () => messageBoxService.ShowMessage(message, header, MessageType.Information)
);

Customize IMessageBoxService interface to your needs, and pick up a better name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...