【问题标题】:Design Time Data for Dependency Properties?依赖属性的设计时数据?
【发布时间】:2014-02-21 19:00:33
【问题描述】:

我正在构建一个UserControl,它有几个DependencyProperties,用于绑定控件的XAML。

当我使用 MVVM 时,我通常会创建一个设计时 ViewModel,因为我发现这样可以更轻松地设置我的视图布局,而无需运行应用程序。

有没有办法在 UserControl 中将 design time 数据设置为我的依赖属性?

【问题讨论】:

  • 您最终不会将 UserControl 的 DP 绑定到视图模型吗?
  • @McGarnagle 我正在为另一个项目中的某人创建一个控件以供使用。他们将拥有 ViewModel。我有一个“测试”项目,我将在其中创建一个 TestViewModel 来使用我的控件,但我希望我的控件是“独立的”。所以我希望能够在控制级别设置设计数据。

标签: wpf xaml mvvm user-controls dependency-properties


【解决方案1】:

在你的xaml 中定义这个

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d:DataContext="{d:DesignInstance prefix:ViewModel}"

这应该会给你 ViewModel 中的属性..

【讨论】:

  • 只要有 Binding 属性,就可以使用 DataContext。但是在 UserControl 中,您绑定的是控件的属性,而不是 DataContext。有办法克服吗?
【解决方案2】:

我建议将控件的DataContext 设置为TestViewModel 实例。您可以使用DesignerProperties.IsInDesignMode(Silverlight 为DesignerProperties.IsInDesignTool)确保仅在设计模式下完成此操作:

public MyUserControl()
{
    if (DesignerProperties.IsInDesignMode)
        DataContext = new TestViewModel();
}

【讨论】:

  • @Dzyann 没有问题——我猜“IsInDesignMode”是我的意思。我的错,我习惯在 Silverlight 中工作。
  • 我没有注意到这是一个 Silverlight 属性。但是 IsInDesignMode 它也没有出现(可能无法从代码隐藏中访问?)。我尝试使用 DesignerProperties.GetIsInDesignMode(this) 甚至 (bool)GetValue(DesignerProperties.IsInDesignModeProperty) 但它不起作用。设计师没有显示任何东西。
【解决方案3】:

这是我实现目标的方法。如果除了依赖属性之外还想使用继承的数据上下文,这将不起作用。

  1. 将控件的数据上下文绑定到控件本身:

    <UserControl ...
                 DataContext="{Binding RelativeSource={RelativeSource Self}}">
    
  2. 在控件中使用“普通”绑定:

    <UserControl ...>
        <TextBlock Text="{Binding MyDependencyProperty}"/>
    
  3. 添加一个设计时数据上下文,其属性与控件的依赖属性同名:

    <UserControl ...
                 DataContext="{Binding RelativeSource={RelativeSource Self}}"
                 d:DataContext="{d:DesignInstance local:DesignTimeViewModel, IsDesignTimeCreatable=True}">
    
    class DesignTimeViewModel
    {
        public string MyDependencyProperty { get; } = "The design-time value";
    }
    

在运行时它将绑定到依赖属性,在设计时它将绑定到 DesignTimeViewModel 属性。

【讨论】:

    猜你喜欢
    • 2013-08-12
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多