如何使用D:DesignInstance有没有默认的构造类型? [英] How to use d:DesignInstance with types that don't have default constructor?

查看:1043
本文介绍了如何使用D:DesignInstance有没有默认的构造类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

这篇关于如何使用D:DesignInstance有没有默认的构造类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆