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).
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With