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 IMultiValueConverter and 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.
class MyViewModel : INotifyPropertyChanged
{
public MyViewModel()
{
// Call service to populate _dictionary here...
}
private Dictionary<string, string> _dictionary;
private string _code;
public string Code
{
get { return _code; }
set
{
_code = value;
Description = _dictionary[_code];
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Description"));
}
}
public string Description { get; set; }
}
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:
<TextBox Text="{Binding Code,UpdateSourceTrigger=PropertyChanged}" />
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.
If you put it in the viewmodel you won't need a converter.
Simply expose a Code property in your VM and bind the label to that. Then in the Code setter you use your dictionary to update your Description property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With