Getting data from a view in MVVM? - silverlight

I have a silverlight bing map application. I am using the MVVM pattern with PRISM.
The bing map has a "BoundingRectangle" property that is not available in XAML, but it is available via code behind. Of course this does me no good since I need the data in my viewmodel which doesn't have access to the View's code behind (nor do I want to add it, since I'd really like to try to not use the view's code behind if possible).
Normally, you would do a two way bind to a viewmodel property. The Bing map will surface BoundingRectangle for layers, but not for the base map (that I can find).
I'm not looking for a hack here, just wondering what the best practices or convention for getting data out of a view to a viewmodel that isn't "bindable".
Thanks!

Databinding in Silverlight is just a framework feature that automatically synchronizes data between your view and your view model (if you are following the MVVM pattern). However, there is nothing wrong with doing this yourself!
The two main advantages of the MVVM pattern (other than the usual separation of concerns that most UI patterns provide) are:
It aids unit testing, the View Model can be exercised from your unit test code without a view present.
It helps the developer / designer workflow, reducing the files shared between the designer and developer.
In my experience, having a small amount of code-behind that 'assists' the binding framework does no hard at all!
You can use techniques such as attached behaviours to wrap this code up, but often this just results in a cosmetic improvement.

CraigF,
you can use Mediator pattern, if you use Galasoft Light toolkit then use messenger to send message from view to your viewmodel. Viewmodel register to that message and if recive one set your property in viewmodel and do some logic..

Related

Ambiguous between Microsoft Sample and WPF Rules

I thought we should have no reference from View to ViewModel in MVVM Pattern. but just saw an MVVM Sample from code.msdn.microsoft in which ViewModel implements new Window and shows it;
By using MVVM-Light toolkit you use Messenger to Call or Open new Window and Still keep Separate the View and ViewModel form each other. Is it right to reference the View in ViewModel? Or it is wrong;
Do you suggest to call Views Directly from ViewModel for large(or medium) projects?
http://code.msdn.microsoft.com/windowsdesktop/Easy-MVVM-Examples-fb8c409f
YAGNI.
Level of effort and complexity.
MVVM is just a pattern. A pattern you don't have to follow. Any little tool I write for my own use just uses a model, a viewmodel, and a view. The viewmodel exposes all properties I need for the view by INotifyPropertyChanged. The data is moved back and forth from viewmodel to model manually using ViewModel.FromModel(model) syntax. I don't bind to my models. I only use the model when saving/loading data; I don't hang onto it. My views are generated using dataTemplates and dataTemplateSelectors. If I have a property that should change the layout I expose that on the viewmodel and use a selector. Otherwise, I have a datatemplate for every viewmodel object. And it just works.
I call this a form of MVVM, even though it doesn't any toolkit or the exact MVVM pattern that Microsoft describes.
I would personally implement a service to drive commands from the viewmodel to generate new views and hookup the viewmodel. But that's because I have MVC experience, and I think generating views is easier to do using the MVC pattern, whereas desktop views work better using the MVVM pattern.
All my views are composed with contentControls. Setting the content is setting the viewmodel.
So I use a hybrid.
If your software isn't so complex to need the complete Microsoft endorsed MVVM pattern, why create the overhead code IMO. YAGNI.
IMO, having a strong reference from the ViewModel to the View has 2 problems:
It breaks the testability of your ViewModel code. This means you won't be able to Unit Test your code so easily, and if you do you'll have to account for Dispatcher issues and the like.
It makes your ViewModels dependent on WPF assemblies and types. This means you won't be able to literally copy and paste your ViewModels into other applications or platforms such as Xamarin.Android or the like
If none of these are important to you, I don't see any reason why you wouldn't. Not doing so creates additional overhead in your code, by having to implement WindowManagers and whatnot.

MVVM - Pertaining to WPF command binding standards

I think I have a pretty good understanding of the MVVM design model, however I have a quarm with it in regards to WPF, Command bindings and how we are meant to use them.
To bind commands to the XAML directly we are meant to implement the ICommand interface within the ViewModel. Now, the ICommand interface is part of the PresentationCore.DLL, which, correct me if im wrong is part of WPF not the base .NET framework.
Isnt the whole point of the ViewModel and Model that it should be totally UI independant? For example, if I implement ICommand in my ViewModel and use it as a data context in order to bind commands from the XAML, isnt my ViewModel then dependant on the WPF frame work (in particular the PresentationCore.Dll).
What I mean is, if I was to go and try to use my Models and ViewModels in lets say a Windows Forms environment, I would have to reference the PresentationCore.DLL even though I shouldnt need it because im using Windows Forms not the WPF framework.
This seems a bit odd to me, am I missing something here? Is there another way I should be doing it to keep my Model and ViewModel totally UI and UI Framework independant, but still be able to utilise the Command binding in XAML?
Thanks in advance!
I also had this kind of problem but not in wpf but in POCO classes. What i did was I created two partial classes in two different assemblies. Like you create one partial class which is not presentationcore.dll dependent in your VM project and create its partial class in another assembly(say WPFVM) which implements ICommand stuff. Now for Winforms stuff add only VM project reference to View project and for WPF stuff add references of both VM and WPFVM to the View project. I hope this will help.
The point of MVVM is to have the view just be a view, and nothing more. Putting ICommands into the view model helps this as it pulls the code away from the view. Where you will run into problems is if you have to access something on the view that is not a dependency property, which means you can not bind to it.
In my opinion MVVM is very popular with the WPF, Silverlight because it naturally fits into it. The data binding concept in the XAML allows the Views & ViewModels to be bridged using a single property which is the DataContext. As no longer your logic is tied to controls, you get better testability, design-code separation and maintainability. You may be able to implement the MVVM pattern in other places also, but in WPF and Silverlight, it fits so easily due to its data and command binding support. I have read somewhere that, Don't take patterns religiously. They were made to make your life simpler rather than giving you more problems while following it. For Winforms i think there are better patterns, If you are focusing in reusing the business logic, move them out of your ViewModels to seperate classes something like serviceproviders or serviceagents and share them between your Winforms and WPF apps.
This has changed in .NET 4.5 compare
.NET Framework 4.5
.NET Framework 4

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.

Where should the viewModel be created?

I have seen a few examples where the viewModel (in Silverlight apps) is in the UserControl.Resources XAML section of a View. I read that for using Blend, this is a good place to have it (as it gives the ability to see sample data in Blend).
However, is this the best place to have the viewModel? I read that the "view has to push services to the viewModel". What does this mean and where else could or should the ViewModel be created?
Thanks.
JD.
There are lots of ways that the View and the ViewModel can be connected. The simplest approach is using the Resources like you mention or even easy just setting the DataContext of the View in the Xaml to an instance of the ViewModel.
From there things get more complex and really it depends on the framework you use:
Silverlight.FX - Uses a View base class with a Model property.
MVVM Light - Uses a ViewModelLocator.
Prism - Controllers
Caliburn - Presenters
So the approach you take will depend on what style you like. There are many ways to do this and right now there are a lot of MVVM frameworks showing up.

Is Databinding a good way to connect a view to a model

I am thinking about the design of a WPF or Silverlight application. I am planning to use MVC (or another such design pattern)
Witch ever of the design patterns I choose, I need to connect to view to the model (or presenter) – is databinding a good way of doing this?
(In the past with WinForms applications I have found that Databinding give lots of problem in the long run and does not fulfil its promise. It is the same with WPF and Siverlight?)
Yes, you should definitely definitely use data binding. While WinForms and ASP.NET were always a struggle to get anything data bound consistently and in a maintainable manner, Silverlight and WPF are built from the ground up for data binding pleasure.
Binding is two-way so you don't have to write tedious plumbing code to move data in and out of your model. Just implement INotifable and away you go.
Converters allow you to write code to handle the way things are bound if the defaults aren't working. Using converters (which are dead-simple to write) you can bind booleans to visibility settings, strings to images, integers to background colors, and so on. The sky's the limit.
Patterns such as MVVM are perfect for the rich data-binding support in WPF and Silverlight. MVVM lets you have the best of both worlds: loosely coupled code together with data binding.
Element binding lets you bind the property one element to the property of another element. Together with converters, this gives you impressive power to do things like bind the current position of a slider control to the selected index of a list control. Both ways.
Deep binding means you can bind to the property of a property of your model. Not that you always should, but you can.
Binding is almost magical in its dynamic-ness. As long as your model continues to support the same bound properties, binding will continue to work even if the static type of the model changes. Binding is also crazy flexible. You can bind to collections, interfaces, complex objects, (almost) anything you like.
DataContexts can be used to set up data-binding at a page, control, or container level. Children of the container then inherit the same data-context. This lets you bind once at the page level and then use binding paths for the rest of the page.
I recommend you take a look at the Model-View ViewModel (MVVM) pattern. Here is a very good video you should take a look at: Jason Dolinger on Model-View-ViewModel. Two-way data binding in WPF is very powerful.
be it WPF or Adobe Flex or Winforms , Databinding will always give issues when the application becomes complex. I would prefer to avoid data binding for easier debugging. But data binding runs all around WPF that we can't avoid. Doing data binding in XAML takes away control from the developer.
I think , if we keep the data binding in the code , its much easier to debug.
Imagine , MVVM without data binding , it will look messy. A design pattern that takes advantage of technology is good but a design that is totally dependent on a particular feature is a disaster.
Data binding in WPF goes far beyond what you could achieve in Winforms. It is intrinsic to the platform and prevalent throughout. I would argue you can't understand WPF without understanding its data binding system.
It's not without its pitfalls, to be sure. Broken bindings are often not as obvious as you may like, but improvements have been made to help you identify and flag these issues.

Resources