简体   繁体   中英

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.

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. Just wrap your code in an if statement: 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:

A way to use IsInDesignMode that is MVVM-friendly is shown below.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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