Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine DataContext of a WPF control at design time

Tags:

c#

mvvm

wpf

xaml

How to determine the DataContext of a specific control at design time in a WPF application?

DataContext might be specifically set in XAML, inherited or set somewhere in code and sometimes it is hard to figure out at design time which class the bindings are referring to.

What I usually try to do to find the DataContext class is to search the binding name in VS. For example I see the binding is something like

ItemSource = {Binding Items}

...I will search the text "Items" in order to get to the class but VS sometimes fails to find the searched text (I have several projects in the solution).

like image 891
Nuts Avatar asked Apr 08 '16 06:04

Nuts


People also ask

What is the DataContext in WPF?

The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from.

What is UserControl DataContext?

DataContext is inherited to all lower Elements of the XAML and to all the XAML of UserControl s unless it is overwritten somewhere. By setting the UserControl DataContext to itself, this overwrites the DataContext and breaks Inheritance. Instead, nest it one Element deep in the XAML, in your case, the StackPanel .

What is IsDesignTimeCreatable?

It says in MSDN documentation: d:IsDesignTimeCreatable In the d:DesignInstance markup extension, specifies that the design instance is created from your type, instead of a designer-generated substitute type.


1 Answers

I would like to add an approach to StepUp´s listing:

The design instance:

Just like you can define a run time data context, you can add a data context that is specifically for the design time via:

    <Usercontrol    x:Class="MyUserControl"  
                    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"
                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                    xmlns:viewModels="clr-namespace:MyProject.ViewModels"
                    d:DataContext="{d:DesignInstance viewModels:MyViewModel}"
                    d:DesignHeight="300"
                    d:DesignWidth="600"
                    mc:Ignorable="d">
    </UserControl>

In Visual Studio you can then use IntelliSense for bindable properties and if your view model has an uncomplicated or even parameterfree constructor, it will be created in the Designer and you can test trigger or converters without having to start your application.

like image 69
lhildebrandt Avatar answered Sep 26 '22 10:09

lhildebrandt