[英]XAML Designer Crashes with Self-Registering ViewModel
如果设置为数据上下文的视图模型在静态类中注册,则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);
}
有没有办法解决? 也许#指令?
您可以使用DesignerProperties.IsInDesignMode在设计模式下抑制执行。 只需将代码包装在if语句中: if(!DesignerProperties.IsInDesignTool)
但是,通过调试设计器异常来找到问题的根本原因通常是个好主意。 这是一篇很好的文章,可以帮助你入门。
对于那些寻求比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类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.