I'm new to .net and MVVM designmodel. I'm stuck now, because in the codebehind file of one of my Views, I ne开发者_C百科ed to get the corresponding Model as an object. How is the relationship here? Is it possible, and is it "the right way to do it"?
The View should access the ViewModel, which wraps the Model, hiding it from the View. If you need to access properties of the Model from the View, get the ViewModel to expose them as properties that the View can bind to.
MVVM doesn't forbid the View to access the Model directly. That's a common misunderstanding in the MVVM community.
Your ViewModel can expose the underlying Model so that the View can access the model directly.
Binding:
{Binding Model.Title}
Code Behind:
((MyViewModel)DataContext).Title
The ViewModel (EmailClient) sample application of the WPF Application Framework (WAF) shows how to access the Model from the View.
ViewModel should have absolutely no knowledge of the view. View should use DataBinding only so no knowledge of the model or ViewModel.
If you need to interact with the view, it all must be through DataBinding. Only on exceptional cases you should resort to code-behind.
So have a property on the ViewModel and bind it to the view.
public partial class MyView : Window
{
private MyViewModel aModel;
public MyView()
{
InitializeComponent();
aModel = new MyViewModel();
this.DataContext = aModel();
}
Now the view will change its controls databindings that bound to public properties of the ViewModel.
精彩评论