Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

.net - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...