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