What should go in [Name]View.xaml.cs files? - c#

I am creating a desktop application using WPF & Caliburn MVVM. In my "Views" directory, I have several files that follow this pattern:
ExampleView.xaml <= this is the actual UI design...
ExampleView.xaml.cs <= what goes here?
Then I also have a ViewModel for each view.
Can somebody explain what should go in the ExampleViewModel.cs and what should go in the ExampleView.xaml.cs? It looks like my ViewModels inherit from "Screen", where my ExampleView.xaml.cs inherits from "Window".
Thanks!

That is your "Codebehind" for the view. Many people use the codebehind to interact with their view. However, many people prefer a decoupled approach called MVVM that uses a viewmodel instead. The MVVM architecture is more unit-testing friendly and easier for code reuse.
So in summary, the ExampleView.xaml.cs is used to interact with your controls on the view.

Well, your views can be inherited from Window or UserControl or other WPF classes. In MVVM the view is the user interface and the view model is an abstraction of the view exposing public properties and commands. Instead of the controller of the MVC pattern, or the presenter of the MVP pattern, MVVM has a binder. In the view model, the binder mediates communication between the view and the data binder.
But your view can contains UI-logic that is not depend on data from ViewModel. This logic can be added to [Name]View.xaml.cs files as View's (and inner control's) event handlers, for example OnLoad, OnResize. It calls Code behind.

I just wrote a couple WPF apps using MVVMLight Nuget and all of my [views].aspx.cs only have the auto-generated code. I didn't need to put anything in the views code behind because it goes in my view model. I also converted some web apps and a couple windows 8 store apps to MVVM and almost completely eliminated all code from the views code behind.
The only time I have put something in the views code behind is maybe to instantiate a view model to go along with that view in very isolated situations.
There is much debate out there whether to have zero code to follow MVVM best or having some code in the code behind is okay. Personal preference and based on work load, complexity, timelines, etc.

Related

WPF MVVM vs Razor Page MVVM

MVVM pattern in WPF has a strong emphasis on completely separating the ViewModel from the UI, and ideally has nothing or very little in the code-behind file. This allows to re-use the ViewModel for different types of interface.
MVVM pattern in Razor Pages has the code-behind as the ViewModel and is tightly coupled with the web logic with OnGet and OnPost methods.
Thus, the carefully-crafted decoupled WPF ViewModel cannot serve as the Web ViewModel (or perhaps can be used from the web page Model?)
Is there something I'm missing, and why is there such a difference between MVVM in WPF (decoupled) and MVVM in Razor Pages (coupled)?
If we were to apply the Razor Pages approach to WPF, then the code-behind would become the ViewModel -- which I've never seen anyone recommend.
To make things clear: WPF introduces a coupling between the view and the view model the same way Razor Pages does. The view model is a data representation layer in order to break the dependency between the view and the model. So the view can be changed without modifying any models. The view model itself is then coupled to the model since it fetches the required data (e.g. from a service or data base).
This behavior is realized in Razor Pages in a unified pattern by having the view models implement the abstract PageModel and by following a convention by providing the appropriate optional action handlers (e.g. OnGet()). Those handlers will be invoked by the framework anytime a HTTP request was issued for the page. You would fetch or manipulate model data based on the request method (e.g. GET, DELETE, POST, PUT, ...) and then present it to the view. The convention describes the naming pattern of those handlers so that the framework can identify them.
So you'll find the same degree of coupling between the layers in WPF MVVM and Razor Pages MVVM. Since the view model in RazorPages encapsulates the context of a specific page the source file naming follows a naming convention ("page name.cshtml.cs") to make the relationship visible in your filesystem. It's not a code-behind file like the partial class file of a view in WPF.
I'm not sure why you insist on using Razor Pages, when there is MVC (Model-View-Controller).
You should use the MVC pattern instead. You get the same razor syntax but decoupled.
Razor Pages were introduced as a form of successor to WebForms (which itself tried to mimic Windows Forms, which isn't about decoupling neither).
If we go a few years back in history, MVVM was to use the full power of WPF's Two-Way Model binding, which acts as a separate layer between the UI and Application layer where one can put presentation logic in (logic tightly coupled to the Presentation, which is an UI concern rather than application layer which is decoupled from the UI).
For that reasons the MVVM's ViewModels also have (additionally to properties for Model Binding), things like Commands and may be Navigation aware (i.e. via Prism's INavigationAware interfaces).
In this context, ViewModels aren't of much value in server-sided web applications, because HTTP by itself, is stateless where ViewModels maintain a state.
Thus the ViewModels in MVC are simply reduced to DTOs (Data Transfer Objects), which has basic validation (through validation attributes). ViewModels in MVC Applications don't have any presentation logic, due to the fact its rendered into HTML and most presentation Logic happens outside via JavaScript (what happens when a button is clicked, how to format a date or currency for a user).
That being said, you don't really need full-fleged ViewModels in an ASP.NET Core application, at least not for the server-sided part. However, if you are using a client-sided technology (Angular, Vue.js, React) you may utilize ViewModels to enhance the functionality and decouple it from the View.
In fact, angular components are pretty much ViewModels and fulfill the same task as ViewModels in MVVM pattern do (one can inject services into it, has 1-way or 2-way bindings, input validation and one puts presentation logic in them).
TL;DR: You don't really need ViewModels as they are defined in MVVM, just DTO-like classes to make consuming them in the (Razor)View Template easier. And don't use Razor Pages for decoupling.

How is MVVM in Xamarin.Forms/UWP/WPF any different from using code behind?

In learning Xamarin.Forms/UWP/WPF tutorials always tout MVVM as the design pattern of choice and I've followed suite, but I've never understood why. To contrast, in asp.net MVC the templated framework is used to great effect, Controllers deliver models to the view (HTML of some sort).
But in the Xamarin.Forms/UWP/WPF and others, we create a completely new class, ignore the code-behind file that cannot be removed and relegate it to telling our view where to look when binding data.
The only reason I could think of that makes MVVM better is if we could supply logic where different VM's could be 'injected' into the same view, maybe that would justify it.Though I have no idea how to do that.
Otherwise, how is creating a view model class better than using the code behind file? Is it really worse separation of concerns just because the view and code behind have the same name and are instantiated together?
MVVM pattern is much cleaner than using code-behind.
Separation of concerns
Imagine you have a view and a code-behind implemented. Now the business comes with a request to completely change the way the controls are presented - replacing them with new controls, changing layout and so on. Chances are, you will be forced to rewrite a lot of code just to satisfy the requirement, because the code-behind is directly tied to the view.
Now in case you have MVVM in place, you can easily swap the View part of the equation for any view which utilizes data binding to the right properties in a View model. You could easily present a single View model in several different ways - like creating multiple different views for different user roles while the view model stays exactly the same, you just choose what to display and how.
What view model actually creates is a middle layer between data and their presentation and makes it possible to more easily transform the data the view uses and change the presentation without affecting the view model if the interface is kept intact.
Data binding
Also if you are meaning purely code-behind without data-binding, the advantages of MVVM become even clearer. When you have a data-bound property that updates after user input in a TwoWay manner, for example if you have a form the user has to fill out, you don't have to remember to fetch the latest "changes" from the control using Text property, you know the latest version is already there in the data-bound property. In addition, you can add validation in the property setter, you can update other properties in the setter as well to orchestrate data handling in a much more abstract way than with code-behind approach, where you are tied to events and having to remember where the data come from and which specific controls and which specific properties you have to update. Imagine you display a given text in multiple places - with data binding you just set a single property and rely on {Binding} to display the text in all bound controls. With code-behind only, you need to remember which concrete controls display the text and when you add a new control, you have to update the code-behind appropriately, which is far less convenient.
Cross platform development
Another example would be having to develop a cross-platform application with native UI using MvvmCross. Here you can decide that some views or some functionality will not be available for certain OS or that you want to just implement it later. This is entirely possible - you just don't provide the UI for that functionality and the view model can stay the same.
View state
Finally - having all view state in code-behind means that when you navigate away, you must store the state somehow and restore it when navigating back because a new page is created. With MVVM you may decide to keep the view models of the navigation stack in memory and when navigating back just set the DataContext of the page to the existing view model instance to get back just in the same state as you left off.
Overall I see MVVM as a great pattern to improve flexibility of your codebase and it makes your solution more future-proof and resilient to changes.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

If we search Google using the phrase "differences between MVC, MVP & MVVM design pattern" then we may get a few URL's which discuss the difference between MVC MVP & MVVM design pattern theoretically like:
MVP
Use in situations where binding via a "dataContext" is not possible.
Windows Forms is a perfect example of this. In order to separate the view from the model, a presenter is needed. Since the view cannot directly bind to the presenter, information must be passed to the view via an interface (IView).
MVVM
Use in situations where binding via a "dataContext" is possible. Why? The various IView interfaces for each view are removed which means less code to maintain.
Some examples where MVVM is possible to include WPF and javascript projects using Knockout.
MVC
Use in situations where the connection between the view and the rest of the program is not always available (and you can’t effectively employ MVVM or MVP).
This clearly describes the situation where a web API is separated from the data sent to the client browsers. Microsoft’s ASP.NET MVC is a great tool for managing such situations and provides a very clear MVC framework
But I have not found a single article which discusses the difference theoretically along with sample code.
It would be really nice if I get an article that discusses the difference between these 3 design patterns (MVC, MVP & MVVM) along with code.
I'd like to get my hands on the source code of 3 similar CRUD apps that have been implemented by these three design patterns (MVC, MVP & MVVM). So that I can go through the code and understand how one should write code for these three design pattern (MVC, MVP & MVVM).
So if any such article exists which discusses how code would look different for these 3 design patterns (MVC, MVP & MVVM) then please redirect me to that article.
Some basic differences can be written in short:
MVC:
Traditional MVC is where there is a
Model: Acts as the model for data
View : Deals with the view to the user which can be the UI
Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed.
MVP:
Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.
MVVM
The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM.
Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.
MVC, MVP, MVVM
MVC (old one)
MVP (more modular because of its low-coupling. Presenter is a mediator between the View and Model)
MVVM (You already have two-way binding between VM and UI component, so it is more automated than MVP)
Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx
Let's First look at MVC
The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.
There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.
There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.
The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.
MVP – Model View Presenter
Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:
The input begins with the View, not the Presenter.
There is a one-to-one mapping between the View and the associated Presenter.
The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.
The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.
MVVM – Model View View Model
So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:
The input begins with the View, not the View Model.
While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.
MVP:
Advantages:
Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.
Disadvantages:
1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.
3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.
MVC:
Advanatages:
Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.
Disadvantagaes:
Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.
MVVM:
After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.
Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.
The image below is from the article written by Erwin van der Valk:
The article explains the differences and gives some code examples in C#
MVC vs MVP vs MVVM
MVC - Model View Controller
View(.xml, .storyboard) - Controller(Activity, Controller) - Model(Others)
View - rendering UI
Controller is bound with View
MVP - Model View Presenter
View(.xml, .storyboard, Activity, Controller) - Presenter(plain Class) - Model(Others)
MVVM - View Model ModelView
View(.xml with data, view.swift) - ModelView(ViewModel, ObservableObject) - Model(Others)
Android DataBinding, SwiftUI
MVVM uses data binding or two way data binding to connect View and ModelView based on Observation
Sometimes in UI world(iOS, Android) you can find additional object(Router, Navigator, Coordinator) which is responsible for navigation and setting dependencies

MVVM ViewModel lots of properties

I am new in MVVM and I am developping an application. I have a form view with a lot of property. About 50. I can not seperate these into usercontrol because I would break the mvvm principles.
I can not seperate these into model, because these contains logic. PropertyChange, Error change and these would not be poco classes, and these are not the model.
Would it be nice If I kept 60 property in a same viewmodel?
Do I think it wrong?
How would you organize these?
I can not seperate these into usercontrol because I would break the mvvm principles.
I'm not sure what you mean by this. Essentially you'll want to use view composition and break down the view model and views into constiuent parts.
A view is a WPF UserControl (or Window), so if you're using MVVM then you're using UserControl's, it's just conceptually they are considered as views in the pattern.
I would also recommend that you use an MVVM framework if you're using the MVVM pattern, and something like Caliburn.Micro makes view composition incredibly easy.
I would also not recommend using dependency properties for view models, use INotifyPropertyChanged instead.
Most MVVM frameworks provide a base view model type which includes a lambda based method to invoke the PropertyChanged event, thus aiding refactoring.
Please don't use PropertyChanged for 60 Properties. Use DependencyProperty.
For terms of usabilty use the propdp Shortcut from Visual Studio and press Tab twice.
Please refer to this link:
http://www.codeproject.com/Articles/62158/DependencyProperties-or-INotifyPropertyChanged

Struggling to understand MVVM architecture

I'm trying to learn MVVM and WPF and I'm using the MVVM Light Toolkit. Here's what I'm not fully understanding and maybe it's due to an incorrect architecture of my UI.
What I'm trying to accomplish is pretty simple actually. This is a utility application by the way. I want a window that serves as the 'controller' so-to-say that has a set of buttons. Each button should change the content of a frame. Example: one button loads a 'screen' ( or a 'view' if you will ) that allows the user to configure an 'Agency' which is a custom object. Another button loads a list of Users from the Agency that was in the first 'screen'. This 'Users' view needs to also be loaded in the same frame. In fact, as of right now, the window with all the buttons really is only responsible for loading the 'screens' in the frame. The meat of the application will be within all the separate 'screens'
What I am not understanding is 1) how to let each screen/view know about each other since one is dependent upon the other. It seems that in MVVM the ViewModel shouldn't know about anything. But in my case, I need to pass information around ( such as my Agency ).
If I can get some hints on what I need to look into, that would be great.
Thanks!
Some ideas that might connect some of the dots:
You'll most likely have one viewmodel per view ("screen").
Each viewmodel will contain all of the logic for its corresponding view
Viewmodels can and will know about the models (Agency, Users)
Viewmodels can communicate with each other via the Messenger in MVVM Light
Think of MVVM Light's Messenger as an "application-wide eventing system". When you send a message out from one view model, any other view model can be listening for that message/event and react to it as needed.
Does that help at all? Keep your thoughts coming and I'll keep commenting and I'm sure the community will as well :)
Few things:
each of your screens, should be separate view (eg. user control or new window - I suppose you've done that already)
every part of model (eg. Agency, User) you want to display in your application, should be wrapped with its dedicated view model
your views don't really need to know about each other; you can use commands or events on view models to get rid of those dependencies
view model only needs to know about one thing: model it's building on
it's good to think about view as really simple class, with one single responsibility of rendering content; no logic, no code behind (unless it's purely UI/display related) is something to follow
You can try to prepare your models first (if you haven't done that already), then make view models for them (thinking what properties of models you want to expose to views) and once that's ready, build your views basing on view models. Other way around is also viable option - pick whichever feels more natural to you.
One more thing: since you mentioned you can display several screens in one (I assume) main area, think about equipping your view models with something along the lines of bool IsCurrentlyActive property. This way, you can easily show/hide views with button clicks and still utilize binding mechanism.
They shouldn't know about each other. That is what the Messenger is for controllers and views subscribe to the events they are interested in. That way they don't need to know or care where they event originated.
Hmm Kendrick is faster. What he said.
Also it sounds like you kind of want an Outlook type interface, some navigation that loads other views. I had the same question a while ago. How to do Regions in WPF without Prism?
To better understand the MVVM pattern look at this article: WPF Apps With The Model-View-ViewModel Design Pattern
Also I advice you to look at Caliburn Micro framework.

Categories