MVVM scenario with main window and many user controls
I have a main window and many user controls that I want to show/hide depending on the user choice. For example there is a user control called Customer that should get all the customers from a database or a user control that is a form to sign up for a service. And so on. Each of this controls have viewmodel that should get the data from the database. The problem is I don't know hot to set the data context in the right way. My mo开发者_如何学Pythondel is an ado.net entity data model for simplicity purposes.
I tried:
<UserControl.DataContext>
<vm:CustomerViewModel/>
</UserControl.DataContext>
And I'm binding the fields to the model fields but no data are visible. Before I used the methods in MainWindowViewModel and set the viewmodel to a view in App.xaml.cs and called the method:
Views.MainWindow newMainV = new Views.MainWindow();
ViewModels.MainVM mainVM = new ViewModels.MainVM();
mainVM.LoadCustomers();
newMainV.DataContext = mainVM;
newMainV.Show();
But I thought that the main window shoudl have its own viewmodel that would handle commands only and each user control should have its own viewmodel that will get the needed data.
What is wrong with my approach?
Thanks for any help.
In principle there's nothing wrong with setting the DataContext
on a UserControl
in the manner you've described. So I'd suspect there's something wrong in how your binding is set up, or in how your view model's constructor is working. You should be looking in the Output Window for binding errors and putting a breakpoint in the constructor to see what's actually happening when your UserControl
gets instantiated.
You might have a look at the BookLibrary sample application of the WPF Application Framework (WAF).
This MVVM sample application uses Entity Framework data models as well and it is composed of various Views (UserControls).
精彩评论