XAML Designer与自注册ViewModel崩溃

时间:2014-09-03 01:58:53

标签: c# wpf xaml mvvm designer

如果设置为数据上下文的视图模型在静态类中注册,则XAML设计器会使visual studio 2010崩溃。

查看

<Window x:Class="CTL.Editor.View.EditorWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:editor="clr-namespace:CTL.Editor.ViewModel.Editor"
        Height="300" Width="300">
    <Window.DataContext>
        <editor:EditorWindowViewModel />
    </Window.DataContext>
    <Grid>

    </Grid>
</Window>

视图模型:

public EditorWindowViewModel()
{
    ApplicationViewModel.EditorWindows.Add(this);
}

~EditorWindowViewModel()
{
    ApplicationViewModel.EditorWindows.Remove(this);
}

这有什么办法吗?也许是#指令?

2 个答案:

答案 0 :(得分:2)

您可以在设计模式下使用DesignerProperties.IsInDesignMode来执行压力。只需将代码包装在if语句中:if(!DesignerProperties.IsInDesignTool)

但是,通过调试设计器异常来找到问题的根本原因通常是个好主意。 Here是一篇很好的文章,可以帮助你入门。

答案 1 :(得分:1)

对于那些寻求比Postlagerkarte的答案更详细的人:

使用对MVVM友好的IsInDesignMode的方法如下所示。

if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
    ....
}

我的问题是由于ApplicationViewModel的构造函数加载配置文件,显然Visual Studio不喜欢它,没有找到文件或者在运行时没有在正确的位置搜索文件我的代码。

我最终做的是:

public static bool DesignMode
{
    get { return DesignerProperties.GetIsInDesignMode(new DependencyObject()); }
}

static ApplicationViewModel()
{
    if (!DesignMode)
    {
        Configuration = Configuration.LoadConfigurationDocument();
    }
}

注意:ApplicationViewModel上有一个Configuration静态成员和一个加载配置的Configuration类。

相关问题