Tuesday, June 08, 2010 9:26 AM
Hi, I am working on WPF appliation using MVVM and PRISM. While creating the ViewModel for View, I am setting the DataContext in the code behind of view by this.DataContext = new ViewModel();. But heard we should not set it in CodeBehind. But I couldn't understand the rational behind this. Can anyone give me some pointer on this.
Tuesday, June 08, 2010 3:23 PM
You have to link the ViewModel with View anyway and as far as i know there are two possible ways, i.e. using XAML or using Code. I dont see any harm is using code and use this approached while working on MVVM. I wrote few articles on it and almost all of them using this approach. Take a look at
Tuesday, June 08, 2010 4:22 PMthat is the approach I use, It is good to keep as much code as you can out of the code behind in MVVM but everyone of my views at least has that line in the code behind.
Thursday, June 10, 2010 7:28 AMModerator
I think this depends on the situation. For example, you can also create some view from a main window, and the DataContext of that view may be related to some item from a list in the main window, so in this situation, we will set the DataContext in the main window code-behind or via some command according to that item.
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.