开发者

Efficient technique for sending text messages to UI

I have a WPF Windows app. The viewmodel calls a method in the开发者_运维技巧 format of Model.TrySomething(), which returns a boolean if anything in TrySomething logically fails. If false is returned, the UI can throw a message back to the user.

What is the best way to bubble this message up from the model?


This is how we do it on our projects. Works fine:

// your event args might include more properties
public class ShowMessageBoxEventArgs : System.EventArgs
{
    public string Title { get; set; }
    public string Text { get; set; }
}

// example of your model base
public class MyModelBase
{
    public event EventHandler<ShowMessageBoxEventArgs> ShowMessageBox;
    protected void RaiseShowMessageBox(string title, string text)
    {
        if (ShowMessageBox == null)
            return;
        var _Args = new ShowMessageBoxEventArgs
        {
            Text = text,
            Title = title
        };
        ShowMessageBox(this, _Args);
    }
}

// for this sample, this is your view model
public class MyModel : MyModelBase
{
    public void DoSomething()
    {
        // TODO: Do Something
        base.RaiseShowMessageBox("DoSomething", "Complete!");
    }
}

// this is your window or in app.xaml.cs (where we do it)
public partial class MainWindow : Window
{
    MyModel m_MyModel = new MyModel();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = m_MyModel;
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    bool m_Loaded = false; // only once
    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        if (m_Loaded)
            return;
        m_Loaded = true;

        // allow model to show messagebox
        m_MyModel.ShowMessageBox += (s, arg) =>
        {
            MessageBox.Show(arg.Text, arg.Title);
        };
    }
}

Best of luck!


If the message which you want to display is a modal dialog, you can write a service (lets name it MessageDialogService) which is injected in your viewmodel and then call a MessageDialogService.Show() method. This method creates a new WPF window and shows the message.

This service can then be used in any of your ViewModels to show messages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜