I'm moving existing C++/CLI application to C#/WPF. When initial application was written no design was done whatsoever. Application has an ability to load one or more image files (only one image is visible at a time), also there is an option to connect to a microscope and see and save images in real time (images from microscope show at the same image box as the loaded ones). Then, there are a lot of dialogs with different settings. There are buttons on the main view to make different kind of calculations based on currently loaded image files and selected settings.
There is a button to send images loaded to another window which has more functionality - makes a movie from loaded files, calculates statistics etc.
I'm fairly new to C#/WPF world, but want to make a nice design. I did some research and it looks like MVVM is the pattern that is mostly used in WPF. Now I'm reading about PRISM. I more or less understand what's going on with MVVM, but cannot apply its logic to my situation yet. May be I should stick to MVC?-but there are not a lot of resorces on how to use it with WPF... I found examples on where to put dialogs, but don't know where to put my calculations... looks like they don't belong to either of M/MV/V. Also, I cannot understand if I can have only one Model associated with many ViewModels.
First of all, this is common misunderstanding.
MVVM is a pattern just like MVC. There is various frameworks that help you with MVVM. MVVMLight, Caliburn is some of the examples. I think you need to learn what MVVM is and then look for different implementations. Personally I wrote my own base View Model class and that's all to MVVM
PRISM is a framework and actually it has almost nothing to do with MVVM. It does provide INotifyPropertyChanged implementation but that's about it.
PRISM is a big framework, it takes time to learn it. It is not something you can start using tonight. However, it is "a la cart" which means you don't have to use everything it provides and can use only what you need.
The more I learn the more I realize that PRISM solves pretty much all the problems you will have while developing big business application with heavy UI. For me, time invested in learning definitely paid back.
It provides regions, modularity, messaging, IoC and other stuff that needed when you build big application. MVVM looks tiny and easy after you see bigger picture..
Related
I have a WPF application that should be compact, with minimal possible memory footprint. The GUI is simple from the point of view of flow, few pages and grids, but quite rich from the point of view of graphics, animations etc.
I have experience writing applications with Prism and I like it very much. But it looks too heavy for simple tasks. It is not a LOB application, but I still need testability, GUI/flow/business separation etc.
Should I use MVVM anyway?
I am not sure if the overhead of using the MVVM design pattern is something I should worry about or not when trying to minimize the memory usage of my application.
Yes, use MVVM if you're working with WPF
WPF is designed so you have a UI layer and a data layer, and this suits the MVVM design pattern perfectly. I find it makes the coding and maintenance much faster and easier.
You don't have to use a full fledged MVVM framework, or even any MVVM framework at all. You can pick and choose the parts you're interested in using (a base object that inherits INotifyPropertyChanged, a RelayCommand or DelegateCommand, the messaging system, etc) and drop all the rest. Or you can build your own.
The amount of overhead is minimal and definitely not worth avoiding the pattern for, however some MVVM frameworks do include unneeded features and can cause some overhead, so be sure you only pick the pieces you want out of them.
The point is, use the MVVM design pattern if you're working with WPF. It will make your life, and any future developers that work on the project lives, much easier :)
I really would recommend using MVVM.
We used the pattern in a huge project and it worked well, with the following recommendations:
we use the very useful, and as the name says, light, MVVM Light Toolkit lib
we do not use the ViewModelLocator thing. Too hard to make it work when you dynamically instantiate Views. The good old this.Datacontext = new TheViewModel(); in the code-behind is fine
we do not use the Messenger thing. Too complicated for very little benefits. A good old event fired from the view model is way more simple IMO.
we do not use the EventToCommand thing, which complicates the XAML for nothing in lots of cases.
we do write code behind when the code is purely related to the view. For mouse gesture features (drag & drop...) or other specific UI things, code-behind is fine for control events handling.
First of all: Yes, MVVM is a recommend way of how to architect an C# / WPF application
Second: You can use MVVM with not framework at all, then it is as lightweight as you build it.
Look here for an overview of possible MVVM frameworks:
SO in depth discussion of different MVVM frameworks
I am pretty new to WPF and I have an discussion this morning with my architect who is from C,C++ background.
We are trying to create a video calling application which depends on native dlls by making PInvoke. The WPF application is mainly the UI and in code behind we are making Pinvoke Calls for Video /Audio and listing the available drivers.
So If we are talking Data as from database then there is not much of the "Data" involved in our application.
The WPF application we are trying to modify is Boghe and surprisingly they too are not using MVVM.
While I am keen on implementing MVVM the architect points it as unnecessarily splitting the files in to 3 parts.
He says if we want to change any thing in the view like changing a button or any control then it can be directly done in code behind. Why then use MVVM?
Though I have theoretical answers but can't help but agreeing to his point. Is he actually right?
He says if we want to change any thing in the view like changing a button or any control then it can be directly done in code behind. Why then use MVVM?
Of course it can be done this way. The question is whether it should be done this way.
For a fairly small code base, you can probably get away with mixing up data access, core logic, and UI manipulation in code behind. In the long run however, that will not make for maintainable or testable code, and the mess is likely to get worse over time and turn into spaghetti code. Take my word for it, because a good portion of my time at work is put into reversing such old messes.
Some consequences of mixing everything up in code-behind are:
Code that fundamentally violates the "Single Responsibility Principle" (SRP).
Code that's hard to understand because it does very different things all in the same place.
Code that breaks easily. I change something here and for some arcane reason, some feature breaks over there.
Code duplication / violation of the "Don't Repeat Yourself" (DRY) principle. You often find the same logic in several places. Is this accidental, or on purpose? If I change logic here, must the same/similar logic over there be changed too?
Note that with the exception of the first point, these are not theoretical concerns, but very real, immediate problems of your typical "legacy" code base.
In my opinion, it's not entirely correct to say that MVVM introduces more code-behind classes. This is clearly a statement from someone who does not appreciate the fundamental separation of concerns that comes when you isolate the data, business logic, and UI logical layers from one another: Even with MVVM you have only one code-behind class for your views. The other two classes (yes, there will likely be two more) simply can't be considered "code-behind" because they aren't directly tied to the view / designer.
Short Answer: No!
ViewModels are not the same as Codebehind in different files.
With a proper MVVM implementation, you do not have a codebehind, or at least
a very small one.
But in the ViewModel you do not have direct access to the window, as in MVVM
the communication between ViewModel and View is done over Binding, there is
no direct reference to a View (normally).
MVVM brings in some enormous advantages over view centric approaches.
It is testable, it is far easier changeable, it is an adapter, ...
edit
And if he really is your software architect, he should know better...
at least thats what I expected from a software architect
I too agree with stakx and Mare Infinitus; MVVM provides a lot of benefits and is not just creation of multiple code behind files.
From my experience MVVM is the best way to learn and use the power of WPF, it kind of encourages and forces you to use WPF features like Binding, Commands, Styles, Converters etc. I have seen application's being developed without MVVM and they turned out to be WPF application in Winforms style having problems stakx mentioned (and more).
Apart from UnitTesting(which I think is very imp. in your application), re-usability etc. one very important benefit of using MVVM is that it can support multiple views, i.e. you can have multiple UI's for your application all of them can use same ViewModels; This may not be a requirement for you today but you may require to have a new interface few years down the line or support other platforms like Silverlight or Metro in future, MVVM will save you a lot of effort in that case.
I would suggest you to go through this post which explains real benefits of MVVM and explains other so called benefits (although I feel they are real benefits in practice) - MVVM Backlash
one purpose is that you can unittest your view logic(viewmodel) without the view.
here one nice comment from Rachel regarding viewmodel first approach:
Remember, with MVVM your ViewModels are your application. The View is
just a pretty interface that allows users to interact with your
ViewModels.
If you have only two people in the project, and everyone's all-in-one person, he's right.
But if you do not want designers messing up the controller (or ViewModel), or programmer that changes view to something, you know, as programmers do design.
In addition, You have the clue where to do changes immediately, without searching enormous text files.
Also, the separation by MVVM or MVC is one of basic principles of programming, it's Data-Logic-View separation, and if architect says you not to do it, may be it's time to ask another architect :)
I hope the title reflects what I'm really asking. It seems to me that when people undertake XAML based development whether to use MVVM is not even a question, rather an understood fact. Coming from a background of Winforms and Webforms, I found that we almost never used MVP (for example). It was well understood that the main reasons to go down the MVP path (other than being a purist) is higher level of unit testing, and the ability to share "view logic" with different UIs. As far as the later is concerned, it has never been a requirement in my projects. If anything we might have had several user controls for this purpose.
As far as unit testing, I never found it necessary to test my code behind because it did nothing more than handle UI events and act as a proxy (create instance of and bind) to my business layer. I can understand if people bypass the business layer and create instances of their favorite data access layer directly in the code behind, then apply business logic to it right there, where MVP would be a huge benefit. In my cause I always front the DAL with a BLL, so where is the real "win" here as far as unit testing?
Point being it was never automatic to use MVP. I am now looking at possibly using Sliverlight (for the first time) in a project and I feel like I'm going to be committing a sin if I don't use MVVM.
I know there are a slew of little things that are MVVM specific perhaps that were not a consideration before when I was making the "to MVP or not to MVP" decision. I've read about Blend support (I don't even have Blend), maybe some other important aspects? The bottom line is though, is MVVM really that much more important to Silverlight than MVP was to Webforms for example? Or are we riding the renaissance days of .NET development where patterns and best practices are taking center stage (sort of like Java).
We moved from Vb.Net winforms to C# and WPF/Silverlight under MVVM. It is definitely a change of pace from our adhock coding. I love being able to create multiple views to work with the same view model. Makes it easy to customize screens for our customers that want it without a whole lot of programming changes.
I found these posts in Stack Overflow that might answer your questions:
Benefits of MVVM over MVC
Why MVVM and what are it's core benefits?
MVVM Unique Benefits
Those have some good answers comparing MVP to MVVM.
Hope that helps.
**** Additionally **
If you were referring to Expression Blend, I used blend when I first learned xaml. Now that I know what I am doing in it, I rarely use it unless I need to do something complicated with animation or whatnot. I use visual studio for coding it since, from my experience, Blend is still cumbersome. Don't get me wrong, it's a great program and does animations great, but it's for designers, not coders really.
From my limited experience with WPF and MVVM, my opinion is this:
MVVM is a pattern, but is not the end-all-be-all of WPF. Especially in the case of MVVM "purists." There are times and places for event handlers and code behind, even in WPF. The benefit of the xaml development and MVVM is the separation of logic from design, but at times, you logic involves your design much more directly than MVVM allows.
I guess the main reason why MVVM is so advocated because of the power of DataBinding.
With web forms for example, you will need to create your own interfaces, framework etc... to implement MVP, whereas in Silverlight/WPF, databinding is just there, so whether or not you use it, it is up to you.
In my opinion, I think MVVM simply adds in a layer of testable view logic (ViewModel) instead of like the MVP pattern where your business logic can really be in the presenter itself.
In summary, if it is already there, easy to use, use it.. it is like you have a car, but u can still choose to walk 10miles to your nearest market, or you can drive (most would advocate you to drive).
Thats my 2 cents.
I have been hearing a lot of hype about MVVM for WPF. When do we use it? Is it a use for everything or does it only have specific uses? Is it worth it for every project?
It can be useful in any project, but I find it particularly helpful in situations where providing a clear separation between business logic, interaction logic, and user interface is required (large applications or applications involving multiple developers/designers).
Model = Business Logic
Contains the model of whatever business process/object I am working with.
ViewModel = Interaction Logic
All the code that controls how the model is accessed and modified (e.g. edit/undo functionality, lazy loading, etc.)
View = User Interface
The interface (defined in XAML) that the user interacts with. I try to minimize the use of code-behind in this layer, pushing that into Attached Properties or the ViewModel.
There are doubtless many other uses for MVVM, but this particular scenario is the one I have found to be the most useful in my own WPF development experience.
I've found it useful even in relatively small projects, if I'm making a lot of use of databinding and an object data model / models.
In terms of WPF and Silverlight?
In theory for everything - every non-trivial project (and possibly even then). Its part of a wider process (it creates separation of concerns and allows for testing and other nice things). Basically if you're going to do it (and I think you probably want to, I certainly intend to with new projects) then you should do it pretty much across the board.
If you haven't already, go watch the video linked from here: http://blog.lab49.com/archives/2650 - I found it very helpful in getting my ideas straight.
Better to ask: when shouldn't you use it? The most obvious example is when data binding isn't appropriate and you have to manipulate elements of the view directly in code - if, for instance, your application needs to update the visual state of hundreds or thousands of visual elements in real time you may not be able to afford the overhead of data binding.
Every time I start on a simple project and think "this is so simple, MVVM would be overkill", approximately 8 hours later I get to a point where I realise that using MVVM would make things much simpler.
So I'd say most of the time using MVVM will actually simplify your UI logic, even if you initially think it will be overkill. Projects have a habit of getting more complex over time, and the separation of business logic and view logic enforced by MVVM enables the project to grow in a far more controlled way than having you business and UI logic all mixed in together.
I'm currently working on a large project, where we implement mvvm, CAL (Composite application guidance) in Silverlight. Of course, level of separation of concerns is very high.. but
1) the code gets too robust.
2) MVVM looks great for small projects ( all these hello-world samples all over the internet), but it reduces your oppportunities: For example, Routed events (great instrument) are still EVENTS, but, as you know, it's strictly forbidden to use them directly, as soon as this is code-behind) if you want to follow mvvm.
3) Command Binding STILL doesn work properly in Silverlight(.net4.0, vs2010). It's a long story, just keep that surprise in mind, when your CanExecute delegate will not fire at app start.
A good answer to your question is "MVVM is good for projects with simple UI logic".
Thanks, Ilya.
I'm taking an vanilla WPF application and converting it to use the MVVM pattern. During my evaluation of the code, I made up a list of topics that I'd need to know about before converting the application. My list looks kinda like this:
dynamically loading xaml (although this is specific to my app)
binding xaml to view model commands (buttons, toolbars, menu items)
hotkeys
binding view model commands to events (window size changes, mouse events, etc)
handling dialogs (message boxes, file dialogs, user-designed dialogs, etc)
I already have various solutions for each item, so I'm not asking about how to do them. My actual question is: am I missing anything? What else is there that I'd need to know about?
Another way to see it is if I were making a WPF WVVM toolkit. What kind of features and functionality would it need so that developers can create MVVM apps?
Thanks!
I think you've got the basic MVVM issues. What you might still need is "What do I do when my app becomes too complex for MVVM?" That happens fairly quickly--more than a couple of views, and you get a view-model explosion, or you get monolithic view models that become cumbersome and very difficult to maintain.
I'd suggest looking into the Composite WPF (Prism) framework as one solution to that problem. Prism is an architectural framework that simplifies partitioning an application into modules that are more-or-less independent of each other. Each module can have a view or two (one is probably most common), and each view can have its own view model. It does a great job of organizing communications among modules in a very loosely-coupled way. The modules load into a Shell window that can be configured however you need.
Hope that helps!
You might also want to set infrastructure for some common functionality like copy/paste search buttons etc.
The first problem I faced when switching over to the MVVM was to binding events/routed events to handlers in the VM. There are no built-in or default way of doing this. I do have a helper to achieve it but its a problem you may need to consider as event handing in the code behind also defeats the MVVM pattern.