如何强制 Visual Studio 2010 在设计时忽略 WPF XAML 声明的 DataContext?
我经常使用声明性 DataContext 设置 WPF UserControl:
<UserControl...>
<UserControl.DataContext>
<local:SomeModel x:Name="Model" />
</UserControl.DataContext>
</UserControl>
在设计模式下,Visual Studio 将尝试实例化 DataContext。但是,当 DataContext 从配置文件中提取数据时,Visual Studio 2010 将抛出错误,例如:
无法创建实例 “某个模型”。
当错误被抛出时,设计时的经验就没有什么价值或没有价值。如果我注释掉 DataContext,则 Visual Studio 2010 设计模式将按预期工作,无需 DataContext。
有没有办法让 Visual Studio 在设计时忽略 XAML 声明的 DataContext?
Quite often I will set up WPF UserControl with a declarative DataContext:
<UserControl...>
<UserControl.DataContext>
<local:SomeModel x:Name="Model" />
</UserControl.DataContext>
</UserControl>
When in design mode, Visual Studio will attempt to instantiate the DataContext. However, when the DataContext is pulling data from a configuration file, Visual Studio 2010 will throw an error such as:
Cannot create an instance of
"SomeModel".
When the error is thrown, the design time experience is of little or no value. If I comment out the DataContext, then the Visual Studio 2010 design mode works as expected, sans DataContext.
Is there a way to have Visual Studio ignore the XAML declared DataContext at design time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
覆盖(或用“新”隐藏)数据上下文并使用 System.ComponentModel.DesignerProperties.GetIsInDesignMode() 返回适当的上下文。
为了获得奖励积分,请将条件分解包装在预处理器指令中和/或使用明智的 ConditionalAttribute() 以确保这种额外的噪音不会进入生产环境。
Override (or hide with 'new') you data context and make use of System.ComponentModel.DesignerProperties.GetIsInDesignMode() to return the appropriate context.
For bonus points, wrap your conditional break up in pre-processor directives and/or make use of judicious ConditionalAttribute() to ensure this extra noise doesn't make it out into a production environment.
不确定我是否完全理解,但我使用此扩展方法来检测设计器何时运行我的代码:
Not sure I understand completely, but I use this extension method to detect when the designer is running my code: