I am recently starting with WPF and MVVM and I have been given the case in which it would be useful for me to bind the DataContext
in the Code Behind since the ViewModel receives the window as a parameter.
My ViewModel has a constructor like the following:
public ViewModel(Window window)
{
...
}
So in the CodeBehind I can set the DataContext
as follows
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel(this);
}
The problem is that in this way all the benefits of IntelliSense for Bindings are lost, which I would like to avoid.
I tried to create a default constructor so that it binds in both places:
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
Which worked without a problem, but then I noticed that two instances of the class had actually been created ViewModel
.
Is it possible to set the DataContext within XAML, so as to have IntelliSense, without creating an instance?
You are creating an instance in the XAML:
And also in code behind:
That is why it creates 2 instances of the class even though in the end only one is used.
Try using
d:DataContext
that allows you to assign a model with predefined values to a view so you can preview it in design mode and you can also use the Intellisence in the bindings and it doesn't create an instance at runtime.Declare a resource in your XAML by assigning the values you want it to display in design mode:
So in the main element you assign the design context to it by searching for it with
StaticResource
:So then you can use the benefits of Intellisence in the bindings with the controls below the element where you declared the context for design mode and preview the values as well.
Remember that you still have to assign the instance of the DataContext in the code behind for it to work for you at runtime.