【问题标题】:Error dialog in MVVM Light ToolkitMVVM Light Toolkit 中的错误对话框
【发布时间】:2012-01-26 02:43:38
【问题描述】:

我在 WPF 应用程序中使用 MVVM 轻工具包,并从外部源获取数据。我的 MainViewModel c'tor 看起来像这样:

    public MainViewModel()
    {
        try
        {
            GetData();
        }
        catch (Exception e)
        {
            //here i want to show error dialog
        }
    }

我无法发送消息(就像它完成了here)来查看,因为 ModelView 是在 View 之前创建的,所以没有人可以接收消息并显示对话框。解决这个问题的正确方法是什么?

【问题讨论】:

  • 你在使用依赖注入吗?

标签: c# wpf mvvm mvvm-light


【解决方案1】:

使用您链接的帖子中的技术,我会做这样的事情:

public MainViewModel()
{
    try
    {
        GetData();
    }
    catch (Exception e)
    {
        Messenger.Default.Send(new DialogMessage(this, e.Message, MessageBoxCallback) { Caption = "Error!" });
    }
}

private void MessageBoxCallback(MessageBoxResult result)
{
    // Stuff that happens after dialog is closed
}


public class View1 : UserControl
{
    public View1()
    {
        InitializeComponent();
        Messenger.Default.Register<DialogMessage>(this, DialogMessageReceived);
    }

    private void DialogMessageReceived(DialogMessage msg)
    {
            MessageBox.Show(msg.Content, msg.Caption, msg.Button, msg.Icon, msg.DefaultResult, msg.Options);
    }
}

【讨论】:

  • 该问题明确指出尚未创建视图。
【解决方案2】:

You should only throw exceptions from the constructor if initialization fails。在这种情况下,您可以在加载视图时开始检索数据。您可以使用 Attached Command Behavior 从加载的事件中调用 VM 的命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-19
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    相关资源
    最近更新 更多