How to force Visual Studio 2010 to ignore a WPF XAML declared DataContext at design time?

筅森魡賤 提交于 2019-12-12 04:02:54

问题


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?


回答1:


Not sure I understand completely, but I use this extension method to detect when the designer is running my code:

public static class Extensions
{
    public static bool IsDesigner( this Process process )
    {
        if ( process.MainModule != null )
            return ( process.MainModule.ModuleName.Contains( "devenv.exe" ) );

        return false;
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/3304547/how-to-force-visual-studio-2010-to-ignore-a-wpf-xaml-declared-datacontext-at-des

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!