I have a Label that translates a code inserted by the user to the description. For that I am using a Dictionary inside a converter.
This Dictionary is filled in every call to the Converter throw a Service. This is a really ugly thing, and I wanted to have this dictionary in my viewmodel but I have no ideia how to access it from the converter.
Any ideia?
In your view, bind the dictionary as a resource (supplied by the ViewModel). Change the converter to an
IMultiValueConverterand use a<MultiBinding>to bind it to both the value that you need to use for lookup, and to the dictionary that you’re looking up in.See http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter.aspx for more information on converters taking multiple input values, and an example of using one with a
<MultiBinding>.Alternatively, as GazTheDestroyer proposed, put it in your ViewModel.
And instead of binding through a converter, bind to the Description property.
UPDATE
To answer your question about updating, you’ll need to change the binding in your XAML slightly to change the UpdateSourceTrigger. The default for a Text property is to update when the control loses focus, this will change it to every time the value changes:
Further reading is available at http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx
You may have to add some error validation here – every keystroke will alter the value of Description so you may want to include some logic in your ViewModel to only change the value when there is a value to use, or grey out a value that does not correspond to the (half-finished) code. These are usability things though, you can play around to find what is best for your application.