MVVM and Binding for different classes

Asked

Viewed 144 times

0

If in the Viewmodel Model View pattern I have:

  • Mainpagemodel.Cs

  • Mainpageviewmodel.Cs

  • Mainpage.Cs

  • Mainpage.xaml

MainPage.cs is also part of my layer View? If so, it is to her that I must delegate the responsibility of "visual interactivity" of MainPage.xaml? How to hide elements or methods having only a visual function, for example?

If so, how do I get inside the MainPage.xaml give a Binding directed to a function of MainPage.cs? whereas within the MainPage.xaml I have a Page.DataContext what makes all Binding go by default to the MainPageViewModel.cs

  • See if you can clear up your doubts here: http://netcoders.com.br/blog/introducao-ao-mvvm/

1 answer

2


By default, when you create a visual element (Window, page, usercontrol) two connected files are created. One is . xaml and the other is .cs. ". Cs" is the so-called 'code-Behind' which is nothing more than the complete code file of the visual element, in the constructor of that code there is a method call to "Initializecomponent()" which is nothing more than reading the file . xaml and its transformation into C#file. Now, answering the questions.

1 - Yes, the Mainpage.Cs file is part of the view, as it is the code-Behind of that element.

2 - It depends on how you are working. Code-Behind already has native access to all view controls that Voce declared "x:Name". So, using this file to only delegate functions to the view-model is valid in MVVM, but using it for UI logic is not MVVM.

3 - To hide the control in code-Behind, just remove the tag "x:Name" from the control in the xaml file. Methods that only have visual function can be used in code-Behind, would be the example of animations that can be a little complex in the code xaml.

4 - You do not need to give a Binding to Code-Behind elements, just use "x:Name" and you will be able to access it.

The MVVM standard is exactly this, using Datacontext to connect the View-Model (which will have the logic of view functionality) through Bindings. As a practice of Pattern, I strongly advise to maintain the logic in the view-models and if you need visual methods like animations, then you can leave in the code-Behind.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.