Search code examples
c#.netwpfxamlexpression-blend

Design time data for both ViewModel and DependencyProperties?


I've been using the d:DataContext property to provide design-time representations of my view models to my views, but I've now encountered a situation where my view has also has XAML bindings to a number of a number DependencyPropertymembers I've declared in the view control that I'd also like to populate with design time data.

How can I provide design time data for both my ViewModel (via sample data) and the control's dependency properties?

Obviously I can just roll all of the properties into my ViewModel to avoid the problem, but I'd rather not, if possible.


Solution

  • A workable solution for my case was to use d:DataContext to provide design-time data representing my view model and use the Binding FallbackValue property to provide the design-time data for my View UserControl's dependency properties.

    If no DataContext is provided, these fallback values will leak into run-time, but for a MVVM view this shouldn't really be an issue.

    <UserControl
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             x:Name="myView" 
             x:Class="Example.MyView" 
             mc:Ignorable="d"                        
             d:DataContext="{d:DesignData /SampleData/MyViewModelSampleData.xaml}">
    
            <Label Content="{Binding ElementName=myView, Path=ADependencyPropertyOnMyView}"/>
    
    </UserControl>