MVVM and Binding for different classes

0

If in the Model View ViewModel pattern I have:

  
  • MainPageModel.cs

  •   
  • MainPageViewModel.cs

  •   
  • MainPage.cs

  •   
  • MainPage.xaml

  •   

MainPage.cs is also part of my View layer? If so, is it that I should delegate responsibility for visual interactivity to MainPage.xaml ? How do I hide elements or methods that only have visual function , for example?

If so, how do I get inside a Binding that is directed to a function of MainPage.xaml ? Whereas within MainPage.cs I have a MainPage.xaml that makes entire Binding go by default for Page.DataContext

    
asked by anonymous 17.08.2016 / 21:39

1 answer

2

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

1 - Yes, the MainPage.cs file is part of the view because it is the code-behind of this element.

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

3 - To hide the control in the code behind, just remove the "x: Name" tag 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 bit complex in xaml code.

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

The MVVM standard is exactly that, use the DataContext to connect to the View-Model (which will have the view functionality logic) through the Bindings. As a practice of the pattern, I strongly advise you to keep logic in view-models and if you need visual methods like animations, you can leave it in the code behind.

    
16.12.2016 / 19:36