MVVM Localization - Localized resources in View vs. in ViewModel? - wpf

Is localization a responsibility of the View or of the ViewModel? Initially, I thought that it clearly belongs into the VM, as it is just data that needs to be displayed by the view. What exactly needs to be displayed is not important to the view. In addition, I have made the experience that XAML is more brittle than ViewModel code. But in a discussion today, some people strongly believed that localization is the responsibility of the view.
Here's some of the advantages I see for both versions:
Advantages of putting them into the View:
ViewModel is oblivious of localization
You can see the resource key in the XAML
Less code
Advantages of putting them into the ViewModel:
View is oblivious of localization
The View does not need to know anything except for it's ViewModel
It's easier to combine and create more complex strings.
In a Wpf application that uses the MVVM pattern, should the localizable elements (string resources) go into the view, or into the viewmodel? Why? What other advantages and disadvantages are there for the two approaches?
Some background info after comments: Assume that the Localization-backend is based on resx (not LocBaml). In addition, assume there was a framework that (View-Variant) could either transparently replace resource-ids in the view with the string, or that (ViewModel-Variant) would automatically generated INotifyPropertyChanged events for localized properties on the ViewModel.
However, I am mainly interested in arguments why it's better from a conceptual or cleaner-code point of view, disregarding the backend.

Some resources belong to the View, and some resources belong to the ViewModel. I do not think there is a strict rule in that matter. Use your own judgment. Personally, I'm sharing the ViewModel's resource file with the View.

To correctly implement localization in your WPF Application as it was designed, you need to follow the set procedure, so there is not really a choice like you are suggesting. For one thing. you'll need to set the Uid property on all of your UI controls, so that clearly can't be done in a view model. Furthermore, it is common to put all localized string values into separate dlls, so again, you can't do that in a view model.
I don't have the time to describe exactly how to do it right now. Instead, for full details about localization in WPF, please see the WPF Globalization and Localization Overview page on MSDN.

Related

How MVVM with DataTemplateSelector is portable from Silverlight to Flex?

I asked a question here about MVVM In MVVM there can be only one View for each one View Model?
Answer would be to use DataTemplateSelector to get multiple views. Now let's say I need to port to flex. Does Flex have the same paradigm as DataTemplateSelector?
Since Silverlight claims that it is close to Flex then I'd like to see proofs :)
Specifically, there is no "DataTemplateSelector". That is not surprising, though, because they are different stacks... (They ARE extremely similar to each other with regards to feature parity and developer paradigm) In Flex, there is the concept of skins, which are very similar to templates. There is also the concept of item renderers, which closely resemble data templates in repeated views (List, DataGroup, DropDownList, ComboBox, DataGrid, etc)
In the case of item renderers (most likely what you are talking about), the components have an optional itemRendererFunction property which is a function that decides which item renderer to use. It allows for extremely dynamic views to be slapped on top of Presentation Models (they are not called View Models in Flex... they use the original name of Presentation Model... not sure why Silverlight ever changed it to MVVM... I digress).
As for skins on all other (Spark-based) components, you can change the skins at runtime using .setStyle('skinClass', TheSkin)
In addition, you can use IoC containers to glue together Presentation Models with any view. This is actually very easy.
Along the same lines, I once built a very tiny view mapping engine that lets you register views against types and the data binding happens automatically. A lot like the RegionManager in Prism for Silverlight.
If you are interested in how Presentation Model fits within Flex, I have written two articles about the topic:
MVVM vs Presentation Model
Presentation Model for using in Multiple Screens
The second link will have a follow-up posted on Tuesday that describes how you use multiple views on top of the same Presentation Model.
So, yes. There are several solutions to achieve what you want to achieve. None of them are direct, because they are different stacks, but the functionality is certainly there.

Getting data from a view in MVVM?

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..

Why MVVM and what are it's core benefits? [duplicate]

This question already has answers here:
Why use MVVM? [closed]
(13 answers)
Closed 2 years ago.
Why we go for MVVM over MVC or MVP while dealing with WPF?
What extra benefit we get by using this?
Edit:
To be honest , today I had an interview and I have been asked this question. I answered like INotifyPropertyChanged , ICommand,IValue Convertor.. but he was not satisfied. Henceforth I have put up this question
Thanks in advance
I'll point you to a particularly useful video by Jason Dolinger.
Coming from a WinForms world, implementing any MVX style pattern seemed like more hassle than it was worth but after working with WPF for a couple of years now, I can honestly say that I wouldn't consider anything less. The whole paradigm is supported out-of-the-box.
First off, the key benefit is enabling true separation between the view and model. What that means in real terms is that if/when your model needs to change, it can without the view needing to and vice-versa.
Secondly, while your model may contain all the data you might need in your view, you may want to abstract that data in such a way that your model doesn't support. For example, say your model contains a date property. In the model it can exist solely as a DateTime object but your view might want to present it in a completely different way. Without the viewmodel you'd either have to duplicate the property in the model to support the view or modify the property which could seriously obfuscate the 'model'.
You can also use a viewmodel to aggregate parts of your model that exist in separate classes/libraries to facilitate a more fluent interface for the view to deal with. It's very unlikely that you'll want to work with data in your code in the same way that a user will want to or will want that data presented to them.
On top of that, you get support for automatic two-way data binding between the view and viewmodel.
There really is a whole bunch of extra stuff that I could bang on about but Jason say's it far better that I could so my advice is watch the video. After a few days of working like this, you'll wonder how you ever got by without it.
Good luck.
These are mine specific to MVVM
Increases the "Blendability" of your views (ability to use Expression Blend to design views). This enables a separation of responsibilities on teams that are lucky enough to have a designer and a programmer... each can work independent of the other.
"Lookless" view logic. Views are agnostic from the code that runs behind them, enabling the same view logic to be reused across multiple views or have a view easily retooled or replaced. Seperates concerns between "behavior" and "style".
No duplicated code to update views. In code-behind you will see a lot of calls to "myLabel.Text = newValue" sprinkled everywhere. With MVVM you can be assured the view is updated appropriately just by setting the underlying property and all view side-effects thereof.
Testability. Since your logic is completely agnostic of your view (no "myLabel.Text" references), unit testing is made easy. You can test the behavior of a ViewModel without involving its view. This also enabled test-driven development of view behavior, which is almost impossible using code-behind.
The other two patterns are really sort of separate in terms of the concerns they address. You can use MVVM with MVP and MVC (most good samples out there do some form of this).
In fact, MVP (w/ a Passive View, rather than a Supervising Controller) is really just a variant of MVVM, in my opinion.
WPF has better databinding than any other UI framework, which MVVM would be unruly without
MVVM provides unit testability and excellent view-agnosticism, which make it a good thing to use
Baked in support for ICommand and INotifyPropertyChanged are the two biggest benefits. Using MVVM makes it really easy to wire up the commands and plug data into the WPF UI. Things just work.
I personnaly see MVVM not as a benefit, but as an obligation for those who want to use WPF cool features.
WPF is very very heavily built with data binding at the core, to enable separation of UI from Model. But the way data binding is technically done in WPF is somewhat special, as it's tied to classes like:
DependencyProperty
INotifyPropertyChanged
ObservableCollection
Because of this you just can't really write a model the way you want using standard .NET technology. For example, the WPF TreeView is almost impossible to use w/o using data binding and templates. You just can't populate it simply like you would from a generic model in Winforms for example. It must be bound to a hierarchical model using ObservableCollection to represent a node's children.
So let's say V represents the XAML code and it's code-behind counterpart (so it's tied to WPF as a technology), and let's say M represents your model (so it's not tied to WPF UI technology in anyway).
Well, you'll never have this working properly under WPF with only these V & M.
You must add something between the two. Something that's WPF-compatible and understands your model. Something that speaks DependencyProperty, ObservableCollection and INotifyPropertyChanged. That's what's called VM.
As a side note, an alternative to MVVM is to build a V & M (w/o VM plumbing) combination with M being WPF-compatible but still with a reasonable UI independency. Historically, ObservableCollection was in the WindowsBase.dll assembly (that was shipped with WPF), so it really looked weird to bind a generic model to something tied to a UI technology. It's been moved back to System.dll since. Even then, it's sometimes hard to keep a pure VM model w/o tweaking the M specifically for WPF...
The ability of XAML code to databind, as well as the existance of triggers will break the MVP and MVC Patterns.

Binding to ConfigurationSection

I just converted all my settings from AppSettings to ConfigurationSections. It definitely cleaned things up, but I'm having difficulties with the preferences window. I want to use bindings in my WPF window.
Should I store each of the ConfigurationSections in a dependency property and bind to the ConfigurationSection's properties?
Should I use ObjectDataProvider's that calls the ConfigurationManager.GetSection?
Is there another way I can do this?
Off-topic: I find the bindings in WPF to be really powerful, but it's sometimes a bit confusing or difficult to create the bindings. I wish there was better documentation for XAML.
You don't need to do anything special - you can databind to types with plain old properties. All the stuff about dependency properties are only for WPF controls themselves. When it comes to the model against which you bind, there are no particular constraints. You can bind to Plain Old C# Objects (POCOs), although implementing INotifyPropertyChanged is an advantage.
However, instead of binding directly to your Domain objects (it sounds like your ConfigurationSections fit that role), it is often a good idea to explicitly create a ViewModel that deals with view-specific responsibilities while encapsulating the real Domain objects.
Josh Smith's article Patterns: WPF Apps With The Model-View-ViewModel Design Pattern is an excellent introduction to proper databinding in WPF.

Confusion regarding MVVM pattern and dynamic loading of XAML in GUI

Well this question relates to MVVM pattern and i could good and fast answers on this forum so I thought to ask and clear the confusions i had about the pattern.
I am quite new to MVVM approach. I appreciate the pattern and understand the principals behind it. Maybe I have not worked that much with the pattern that’s why there are a few confusions.
If there is a scenario in which I want to load few parts of my WPF page dynamically with XAML and still want to be compliant with MVVM approach.
The confusion is:
Where the logic of loading a view dynamically with XAML reside.
Whether I should have a single ViewModel for my WPF page or each seperate part have its own viewmodel with interactions with other viewmodel classes.
What if I had to build control tree displayed on the GUI using C# code in the codebehind itself.
For the controls created using code should I do the commandbindings in the codebehind of the view itself.
Where the logic for loading goes is something not really addressed by the pattern itself. There's an interesting blog post about this by Ward Bell. There's any number of ways to skin this cat, and they're all compatible with MVVM. Not really the answer you're looking for, I know, but it's honest :). Check out Ward's blog post... you'll get a much more in depth discussion of this topic.
As for whether or not to have a single VM for the page, or one for each control, that just depends. Generally, I have one for the page. If there's some portion that reusable elsewhere, I break it out into a user control with it's own VM, which means we have a VM within a VM. I don't agree with rockeye on this one. There isn't a one-to-one relationship between V-VM-M. You're Models are designed according to business needs, with NO regard to presentation at all. You're ViewModels are designed according to your presentation needs, and may encapsulate more than one Model. In fact, it's very common for them to encapsulate many models.
Like rockeye, I don't understand your last question.
I am also quite new to mvvm, but i will try to answer :
Where the logic of loading a view dynamically with XAML reside
If you mean "how can i show the view associated with my business object?", IMHO, you don't have to care about this. Usually, your VMs have corresponding views. With dataTemplate, you use only VM in the code but Views are displayed automatically.
2 Whether i should have a single ViewModel for my WPF page or each seperate part have its own viewmodel with interactions with other viewmodel classes
It seems you have a top-bottom approach. I see the mvvm more as bottom-up : models (business objects) -> ViewModels -> Views. Every model should have its own ViewModel and view. So you can't have a whole WPF page in a viewModel unless you model represents a page.
3 What if i had to build control tree displayed on the GUI using C# code in the codebehind itself. For the controls created using code should i do the commandbindings in the codebehind of the view itself.
Don't understand. I think you may take a look at dataTemplate, it might be helpfull.

Resources