Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use d:DesignInstance with types that don't have default constructor?

I am binding a textbox to an object, like so:

  <TextBlock d:DataContext="{d:DesignInstance ViewModel:TaskVM }"               Text="{Binding Title}" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown">   </TextBlock> 

Now I am wondering how to make it display mock data during design. I've tried doing something like that:

  <TextBlock Text="{Binding Path=Title}" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown">     <d:DesignProperties.DataContext>        <ViewModel:TaskVM Title="Mock"/>     </d:DesignProperties.DataContext>   </TextBlock> 

However, since TaskVM has no default ctor, I am getting a "No default constructor" found.

I know that when I use d:DataContext="{d:DesignInstance ViewModel:TaskVM }" it creates a mock data type. Is there a way for me to set the properties of this mock type?

Thanks!

like image 263
VitalyB Avatar asked Dec 12 '11 09:12

VitalyB


1 Answers

The default constructor is required for a type to be instantiated in XAML. As a workaround you can simply create a subclass of TaskVM that will have the default contructor and use it as a design time data context.

<TextBlock d:DataContext="{d:DesignInstance ViewModel:DesignTimeTaskVM }"             Text="{Binding Title}" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown"> </TextBlock> 

Another alternative is to set d:IsDesignTimeCreatable to False and a substitute type will be created for you at runtime (using your TaskVM type as a "shape").

<TextBlock d:DataContext="{d:DesignInstance ViewModel:DesignTimeTaskVM, IsDesignTimeCreatable=False}"             Text="{Binding Title}" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown"> </TextBlock> 
like image 159
Pavlo Glazkov Avatar answered Sep 24 '22 10:09

Pavlo Glazkov