WPF - Should a user control be supplied with a ViewModel - wpf

I'm about to use a user control developed by a different team (in the same company) and for the app we're developing we're attempting to describe all the data binding in XAML.
Now if I use a third party user control should I expect them to supply a basic ViewModel with hooks for my code or should I expect to write code to bind the user control to a ViewModel of my choice?
Cheers
AWC

It depends on the scope of the UserControl. If it is particular to the application and is unlikely to be useful elsewhere then yes, a public ViewModel should probably be supplied.
However, a public ViewModel is likely to be less useful where the control is expected to be re-usable. The control may use a ViewModel internally, but this should be kept private. Then the host application uses the control in a similar way to any other WPF control, and creates it's own view model to tie the control to the application.
In essence, a ViewModel is usually particular to an application - it is tailored specifically to the needs of that application. Whereas general purpose controls expose properties and events that allow them to be used in any application.

Write the controller class yourself. A reusable control should not know which type of data it's working with, unless it's specifically written for it. But then it wouldn't be very reusable :)

The control is supplied as a self contained unit. If it has it's own viewmodel internally which has hooks exposed that is all great, but to you it doesn't matter because you cannot manipulate it directly.
If you really feel the need then you should write your own viewmodel for the supplied control, as this abstracts the UI (the supplied control) from the controller (your code). That is one of the purposes of the pattern - to separate concerns, so you can swap out any part with minimal effect on the remaining parts.
But having said that, not every control is going to need its own viewmodel, instead you would use the supplied control as part of a larger user control, and write a viewmodel for that larger control.

Related

How to build re-usable user control, within a user control in WPF?

I'm using WPF with the WAF framework.
I have a piece of UI (let's say it collects the user credentials) that gets presented on multiple views (see image).
I figured, hey, this is reusable, let's put it in its own user control.
I can get everything working fine if I ignore the inner user control and just "flatten" it if you will, but trying to encapsulate it is making me wonder what the best approach is. Should this "credentials" user control have its own dedicated view model? Should it be exposing its data through dependency properties instead? What's the best approach?
I will need to expose the data collected from the credentials control to the view model of the outer user control.
Should this "credentials" user control have its own dedicated view model? Should it be exposing its data through dependency properties instead? What's the best approach?
A UserControl can serve two purposes -
If you want to use it as a "Control" - which is often the case in a situation like this, I would treat it as 100% view. As such, I would not make the UserControl have a ViewModel at all (at least not publically), and expose it's properties via Dependency Properties. This provides the most flexibility in terms of reuse, as the UserControl acts like any other FrameworkElement, and can be dropped in and bound to your own properties in your other location like any other control.
When a UserControl acts as a View for a ViewModel, however, things are different. Here, the goal isn't reuse, but separation of concerns between your View and VM.
This situation sounds more like the first - you want to have a control that can be reused in multiple locations. In this case, this basically becomes a view element.

Authentication and Roles in WPF

I am doing a project in WPF. I got a requirement to authenticate a user and providing accessibilty for the modules based on the role. Do i have a better way to achieve this in WPF.
It will depend in part on how secure you need the code to be.
For all your use cases, though, use a Model-View-ViewModel pattern. In each ViewModel, perhaps best placed in a base class for all your ViewModel classes, include a state variable which returns a string and raises the PropertyChanged event whenever the security state changes.
Base your presentation for each View class on the value of that string, following a pattern similar to the accepted answer to this SO question:
https://stackoverflow.com/questions/3868164/
The answer describes how to do this with boolean values, but you can use any string value other than "True" or "False" if your ViewModel state variable needs more than two states.
All .NET code, including WPF, can be easily reverse-engineered. If your code needs to be more secure than that, that is, if your use case assumes that your users will hack your WPF program, then you will want to obfuscate and/or encrypt much of the ViewModel code, using commercially available products like InishTech's SLPS or Dotfuscator or whatever.
Alternatively, you could use the same MVVM pattern and write a Silverlight application, but I'm not sure if a Silverlight user has access to the binary files the way a desktop WPF user would.

is this bad design? MVVM pattern w/ many commands on single class

There are two common command implementations I've seen by Microsoft. One, given by Josh Smith here,
places commands onto viewmodel classes. Another, given by Robert McCarter here, makes commands accessible via a static class (so we can data-bind to them with x:Static). McCarter's approach relies more on the use of singletons and static calls than I want to take chances with, so currently I've chosen to use Josh Smith's approach. However, my "main" viewmodel has blown up in size with at least 30 commands now, as I have a Ribbon control in the main window. Is this a sign of bad design i.e. a lack of separation of concerns? or is this common for MVVM apps? It just seems like a lot of responsibility for a single viewmodel.
I don't think it really matters if you have many commands in the same ViewModel. Commands are just boilerplate code, they don't really implement anything. If the actual implementation of these commands is in the same ViewModel, however, it could be an issue. You should probably try to break down your class into several components to apply the single responsibility principle.
If you have a ribbon control with a lot of commands on it, you're going to need to have a class that exposes all of those commands as properties. It doesn't necessarily have to be your view model; you could, for instance, create a ribbon view model and then expose an instance of it from your view model.
You can't really separate the concerns here unless you have commands on your ribbon that don't interoperate with the view model.
If you are worried of having many command on you MainWindow ViewModel and using a ribbon, you could try giving a separate ViewModel for every tab you have.
In an application I'm currently developing, for example, I separated each ribbon tab into a separate UserControl (which extends RibbonTabItem, because I'm using the Fleent Ribbon). Those views have their on ViewModels. Actually, those ViewModels are dependency injected using a MEF (Managed Extensibility Framework) importing constructor, as well as the tabs are dependecy injected to the MainWindow using its importing constructor. While this approach is probably a gigantic overkill, it has some flexibily. Note that referencing to command on a certain tab from the MainWindow itself isn't a problem, because the MainWindow's ViewModel can have a tab's ViewModel dependency injected into itself and expose some commands of it; or some command can come in form of a specific ViewModel that is injected into all the ViewModels that need it (the latter is probably the cleaner...)

What MVVM framework is Good For?

i know some Mvvm Frameworks that introduced in this thread
please describe or give me link for that what are them useful for?
not information about MVVM about MVVM Framework.
thanks :)
i want to know :
What Is MVVM Framework?
I think your question is not really precise. As far as I understand, you ask for the features of each framework?!
You can find detailed information here and here. However, at least one of these links has already been given in the thread you mentioned...
EDIT:
Basically, an MVVM framework is a collection of classes which are commonly used in applications utilising the MVVM (Model-View-ViewModel) pattern. This may include messaging systems to communicate between independent parts of a software, dependency injection techniques, base classes for ViewModels, project/class templates, validation mechanisms, commonly used commands, techniques for displaying dialog boxes, and so on...
To completely understand such a framework, you will have to understand the MVVM pattern first. Because only then (or even only after you did your first MVVM project) you will have an understanding of the problems and/or challenges of this pattern.
To use Mvvm framework just simply follow below steps:
You have a model and a view-model with the same name.
View-models are not supposed to be wrappers around models. The job of a view-model is to broker requests for external services such as the loading and saving of data. The data itself, as well as validation and most of the business logic, should be in the models.
I can’t emphasize this enough. Whenever you create a view-model that wraps a model by delegation you introduce a huge hole in your API. Specially, anything with a direct reference to the model can change a property in such a way that the view-model and thus the UI are never notified. Likewise, any changes to calculated fields in the model won’t be propagated back to the view-model.
You have a view and a view-model with the same name.
Ideally view-models are agnostic to the screens they are used by. This is especially true in a WPF application where multiple windows may be sharing the same instance of a view-model.
For smaller applications such you may only need a single view-model for the whole application. For larger applications you may need one for the main functionality and one for each secondary aspect such as configuration management.
You have no code behind.
In absolute terms code behind is neither a good nor a bad thing. It is merely a place to put logic that is specific to a single view or control. So when I see a view with no code-behind at all I immediately check for the following mistakes:
Does the view-model touch specific controls by name?
Is the view-model being given access to controls via a command parameter?
Is EventToCommand or another leaky behavior being used in place of simple event handler?
EventToCommand from MVVM Light is especially bad because it will prevent controls from being garbage collected after they are removed from the screen.
View-models are listening to property changed notifications
If a model has a longer life-span then the view-model that listens to its events then you probably have a memory leak. Unlike views which have an unloaded event, view-models don’t have a good story for life-cycle management. So if they attach an event to a model that may out-last them then the view-model will be leaked.

WPF design question (custom control or mvvm)

Here is the scenario:
I have a visual that displays some data
The data to the visual can come in one of two ways
Via user input through the keyboard or mouse
Via some backend source
Both these data inputs can be of one of two forms
Control data or
Raw data for simple display
Control data causes changes in the visual
Raw data is simply showed as is
In other words, the view is being served by two masters, viz user input and backend input.
An example would be a multi-user game that has visuals controlled by user input
but may also have the same visuals controlled by some backend input (say tcp/ip).
Another example would be a terminal emulator that gets user inputs but also gets data
from another source be it telnet or serial, etc.
I was thinking of writing a WPF custom control for the visual. In other words,
it is a black box that will interpret the inputs and display the results.
Getting user input into this custom control is easy since one can listen for the
appropriate events and handle them as needed. However, how can one listen for the
inputs from the backend? Exposing a dependency property that one binds to does not make
sense but exposing a method on the visual that is called with the data also does not make
sense.
Another choice is the MVVM architecture where the Model is the backend data source
and the View Model does all the work. It gets both the backend data (via the model)
and the user inputs (via appropriate command bindings or some such) and it makes
appropriate sense of these and binds to the View to display these changes.
The advantage of the custom control is that it can be consumed as a control that
takes care of itself so that the consumer has to do very little work to use it
but the problem is getting data to it from the backend. The MVVM method is advantageous because it encapsulates the handling logic, view, etc neatly. The problem is that
this pattern has to be repeated for every backend. Thus, making the visual very bare bones
and exposing all the processing logic outside the control. Basically I want
to make it very easy to consume so that someone can take it and use it without adding
too much external logic to do processing etc. All they provide is their backend data
source that feeds into the visual.
Sorry for this being a lengthy post but I am learning WPF and this is an interesting design
question for me. All ideas, comments, etc welcome.
Thanks for reading.
I would definitely use the MVVM pattern. You get a very nice separation of concerns in your code, and your viewmodel can also be tested outside of the user interface. You may also be able to edit you view in Blend. I don't think that hooking up the viewmodel to the backend is more complicated than hooking up a custom control. You may decide to use dependency injection or a service locator to connect things. By using all these design patterns you get a more decoupled and testable solution.
I'd love to know more about CustomControls but in the mean time I think the best option is to use a UserControl as a DataTemplate:
http://www.codeproject.com/Articles/28060/WPF-UserControl-DataTemplate

Resources