Question

I am building a UserControl that has several DependencyProperties that I use for the bindings of the XAML of the control.

When I work with MVVM I normally create a design time ViewModel, because I find that way it is easier to setup the layout of my Views without having to run the application.

Is there a way to set design time data to my dependency properties in an UserControl?

No correct solution

OTHER TIPS

In yourxaml, define this

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

That should give you the properties in the ViewModel..

I suggest setting the DataContext of your control to the TestViewModel instance. You can ensure this is done in design-mode only by using DesignerProperties.IsInDesignMode (DesignerProperties.IsInDesignTool for Silverlight):

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

Here's how I achieve the goal. This does not work if you want to use an inherited data context in addition to the dependency properties.

  1. Bind the control's data context to the control itself:

    <UserControl ...
                 DataContext="{Binding RelativeSource={RelativeSource Self}}">
    
  2. Use "normal" bindings in the control:

    <UserControl ...>
        <TextBlock Text="{Binding MyDependencyProperty}"/>
    
  3. Add a design-time data context whose properties have the same names as the control's dependency properties:

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

At runtime it will bind to the dependency properties, and at design-time it will bind to the DesignTimeViewModel properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top