简体   繁体   English

XAML Designer与自注册ViewModel崩溃

[英]XAML Designer Crashes with Self-Registering ViewModel

The XAML designer crashes visual studio 2010 if the view model that is set as the Data Context registers itself in a static class. 如果设置为数据上下文的视图模型在静态类中注册,则XAML设计器会使visual studio 2010崩溃。

View 视图

<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>

ViewModel: 视图模型:

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

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

Is there any way around this? 有没有办法解决? Maybe a # directive? 也许#指令?

You can use the DesignerProperties.IsInDesignMode to supress execution while in design mode. 您可以使用DesignerProperties.IsInDesignMode在设计模式下抑制执行。 Just wrap your code in an if statement: if(!DesignerProperties.IsInDesignTool) 只需将代码包装在if语句中: if(!DesignerProperties.IsInDesignTool)

However it is often a good idea to find the root cause of the problem by debugging the designer exception. 但是,通过调试设计器异常来找到问题的根本原因通常是个好主意。 Here is an good article that should get you started. 是一篇很好的文章,可以帮助你入门。

For those seeking a bit more detail than Postlagerkarte's answer: 对于那些寻求比Postlagerkarte的答案更详细的人:

A way to use IsInDesignMode that is MVVM-friendly is shown below. 使用MVVM友好的IsInDesignMode的方法如下所示。

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

My issue was caused by the fact that ApplicationViewModel's constructor what loading a config file and apparently Visual Studio didn't like that, didn't find the file or didn't search for the file in the right place when it was running my code. 我的问题是由于ApplicationViewModel的构造函数加载配置文件,显然Visual Studio不喜欢它,没有找到文件或者在运行我的代码时没有在正确的位置搜索文件。

What I ended up doing was: 我最终做的是:

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

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

Note: There is a Configuration static member on ApplicationViewModel and a Configuration class which loads the config. 注意:ApplicationViewModel上有一个Configuration静态成员和一个加载配置的Configuration类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM