Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a ViewModel on a window in XAML using DataContext property?

Tags:

.net

mvvm

wpf

xaml

The question pretty much says it all.

I have a window, and have tried to set the DataContext using the full namespace to the ViewModel, but I seem to be doing something wrong.

<Window x:Class="BuildAssistantUI.BuildAssistantWindow"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     DataContext="BuildAssistantUI.ViewModels.MainViewModel"> 
like image 877
Nicholas Avatar asked Jan 04 '11 03:01

Nicholas


People also ask

What is 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.

How many ways you can bind a VIewModel with XAML?

There are two ways in which we can bind View and View Model.


1 Answers

Try this instead.

<Window x:Class="BuildAssistantUI.BuildAssistantWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels">     <Window.DataContext>         <VM:MainViewModel />     </Window.DataContext> </Window> 
like image 135
Josh Avatar answered Oct 07 '22 16:10

Josh