WPF Custom Control Design Patterns. MVVM? - c#

I am creating a custom control in WPF, it is the highly unoriginal example of a stock ticker that I am deriving from the Control type. My question is: Are there any recommnded design patterns for controls themselves (as opposed to the app)? I am using MVVM for the application as a whole but just wandered if it is good or bad practice to use such a design pattern with the control itself.
My reasons for thinking of using MVVM for the control is that:
It is a relatively complex control, in that it has a graphing ability and Dependency Properties of Midprice, Average etc etc
To have a ViewMOdel as part of it would make unit testing it easier (or even possible)
Makes the entire coding process easier, especially as I have a bespoke ObservableCollection of point types.
Any thought on the matter would be brilliant. I just don't know if this is good practice or not.
Many thanks

1) Future Extensibility - Which I would say is the core when it comes to control development.
2) Good API Design - Create as much as Proof of Concepts.
3) Comes the pattern - If it is really big control. It is good to go with MVVM. But, learn to compromise it as well. Some times, we'll feel when it comes component development strict adherence to MVVM makes the control really complex.
4) Avoid over exposing of properties - Add properties as and when required. [Control feels it like an abuse, if properties are over exposed. ;)]
5) Make the control Lookless. Refer L for Lookless
General:
Try to make the control blendable from starting. It would help you to realize how good and usable from starting. Above all, it gives much satisfication and easy to track the completeness of the control.
When it comes to selecting a particular feature, think in two aspects:
1) Control's usability and
2) Control's Completeness.

If the control itself is self contained and sufficiently complex to be called a view by itself, I would go with the approach of creating a separate viewmodel for the control itself, like you suggest. Otherwise, I'd just let it live in the view that it's hosted in.

Related

If I am concerned about memory usage, should I avoid MVVM?

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

Can the Architect be right "MVVM only splits the code behind to multiple (3) files "

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 :)

Is MVVM more necessary/important to Silverlight/WPF than MVP to Webforms?

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.

When do we use MVVM?

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.

Is it 'wrong' to make User Controls if it is not for reusability?

I can't decide if it is good or bad to make many user controls. I am only doing it cause I find it easier to work on a control where there are not a lot of components. If something needs to be fixed it is also easier. Kind of like how you split your program up in a lot of classes.
However multiple controls adds a bit more complexity when it comes to passing data around. I guess my question is more if it is normal to create a 'god' class when it comes to GUI programming in winforms.
Almost every video tutorials I see, they only work on one form! While I can use like 5 controls before I have a form.
Reasons to create User Controls in WinForms:
Reuse of functionality.
Encapsulation and data hiding.
Readability and maintainability.
Single responsibility principle.
Design-time editor integration for assignable properties.
Ability to refactor/enhance/reuse in the future.
Have you heard about encapsulation and components? It is just your case.
Well from a Web Developers perspective -- no, I don't believe so. In fact I believe in the NerdDinner book for ASP.NET MVC there's a section where the author(s) creates a partial (similar to usercontrol) for the sake of readability purposes. And these are the top guys at MS who wrote this book.

Categories