George Mauer
George Mauer

Reputation: 122202

How does the VS Wpf Designer instantiate and limit execution of VIewModel code?

The WPF designer has a tough job to do. In order to show you a life view of your screen or component it has to execute code but, since you do not control the designer, it has to do this without producing any side effects.

So how does it do that? What are the rules around execution?

What are the limitations?

Upvotes: 3

Views: 194

Answers (2)

Eli Arbel
Eli Arbel

Reputation: 22749

it has to do this without producing any side effects

No, the designer is not that smart. If IsDesignTimeCreatable is specified, it will execute all code in a public parameterless constructor and in properties accessed by bindings. Specifically, it will popup message boxes, write to files, etc -- or throw exceptions trying (just try it yourself).

If you don't have a public parameterless constructor, it can't create an instance, so no code will run.

Regarding your question about "stack depth limit", I know of no such limitation. If you have a specific case where it's not working, I suggest you ask a specific question about that case.

In most cases where the designer fails it is because of an exception or other non-data-related problems (such as missing design-time resources). You should definitely guard code you don't want called during design-time using DesignerProperties.GetIsInDesignMode (I usually add a property IsInDesignMode to the base view model).

Upvotes: 3

LordWilmore
LordWilmore

Reputation: 2912

This is not exactly answering your question, but to be honest 'how does it work' is not a very specific question.

However rather than dropping this check in to your code-behind, are you aware that you can add something like this to your Xaml?

d:DataContext="{Binding Source={d:DesignInstance Type=namespace:className, IsDesignTimeCreatable=True}}"

This means that you can make a design-time version of your class, e.g. CalculatorDesign : ICalculator, reference that in the Xaml, and each time you change and compile the design-time class the view will update within VS without running any code or having complicated logic in code-behind.

Upvotes: 0

Related Questions