如果DataContext类构造函数抛出异常,则不显示窗口的最佳方法

时间:2014-08-29 12:06:55

标签: c# wpf exception constructor viewmodel

我有Window一个按钮,点击按钮打开NewWindowNewWindow为空(为简单起见),NewWindowViewModel对象为DataContextNewWindowViewModel构造函数调用可以选择抛出异常的方法(例如ExceptinMethod)。如果NewWindow抛出异常,我不想显示ExceptinMethod,我想展示一些MessageBox"窗口无法显示bla-bla .."例如。

实现这一目标的最佳方法是什么?

窗口:

<Grid>
    <Button Click="OpenNewWindow">Open new window</Button>
</Grid>

public partial class Window1
{
    public Window1()
    {
        InitializeComponent();
    }

    private void OpenNewWindow(Object sender, RoutedEventArgs e)
    {
        var window = new NewWindow();
        window.ShowDialog();
    }
}

NewWindow:

public NewWindow()
{
    InitializeComponent();
    DataContext = new NewWindowViewModel();
}

NewWindowViewModel:

public class NewWindowViewModel
{
    public NewWindowViewModel()
    {
        ExceptinMethod();
    }

    private void ExceptinMethod()
    {
        // in fact optionally!
        throw new Exception();
    }
}

1 个答案:

答案 0 :(得分:2)

在您的示例中,只需更改您的代码,如下所示

 private void OpenNewWindow(Object sender, RoutedEventArgs e)
 {
     try
     {
         var window = new NewWindow();
         window.ShowDialog();
     }
     catch(Exception)
     {
         MessageBos.Show("Constructor failed");
     }
 }