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.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论