3

我在我的应用程序 mvvm light 工具包中使用。我想使用我的视图模型中的消息框。那么:我可以Messenger.Default.Register(在 App.xaml.cs 中注册)吗?它必须为所有视图模型注册。我不想在每个 ViewModel 中注册它。我可以调用Messenger.Default.Unregister()停用或关闭事件吗?

谢谢

4

1 回答 1

2

MVVM 和消息框的一种可能方法是简单的事件机制:

public class MessageBoxDisplayEventArgs : EventArgs
{
    public string Title { get; set; }

    // Other properties here...
}
...
public class ViewModelBase
{
    public event EventHandler<MessageBoxDisplayEventArgs> MessageBoxDisplayRequested;

    protected void OnMessageBoxDisplayRequest(string title)
    {
        if (this.MessageBoxDisplayRequested != null)
        {
            this.MessageBoxDisplayRequested(
                this, 
                new MessageBoxDisplayEventArgs
                {
                    Title = title
                });
        }
    }
}
...
public class YourViewModel : ViewModelBase
{
    private void SomeMethod()
    {
        this.OnMessageBoxDisplayRequest("hello world");
    }
}
...
public class YourView
{
    public YourView()
    {
        var vm = new YourViewModel();
        this.Datacontext = vm;

        vm.MessageBoxDisplayRequested += (sender, e) =>
        {
            // UI logic here
            //MessageBox.Show(e.Title);
        };
    }
}
于 2013-03-14T13:26:20.143 回答