如何使用D:DesignInstance有没有默认的构造类型?如何使用、类型、DesignInstance

2023-09-04 01:53:47 作者:Kelly 战士

我绑定一个文本框的对象,像这样:

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>

不过,由于TaskVM没有默认的构造函数,我得到一个没有默认构造函数中找到。

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

我知道,当我使用 D:的DataContext ={D:DesignInstance视图模型:TaskVM}它创建一个模拟数据类型。有没有办法对我来说,设置此模拟类型的属性?

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?

谢谢!

推荐答案

默认构造函数需要一个类型在XAML中实例化。作为一种变通方法,你可以简单地创建 TaskVM 的子类,将有默认的构造器,并使用它作为设计时的数据环境。

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>

另一种方法是设置 D:IsDesignTimeCreatable 和替代型会为您在运行时创建(使用TaskVM类型为形)。

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>