6
votes

I am using WPF and the MVVM pattern in my user interface. In my ViewModel I have a List containing distances in millimetres, which I display in a ListView by binding ListView.ItemsSource to the List. However, I would like the values displayed to use a more natural unit - either metres or feet depending on the state of a "metric" checkbox.

I have written a couple of simple classes, MillimetresToMetresConverter and MillimetresToFeetConverter, both of which implement IValueConverter. Although I can set the Converter property on my data binding to one or the other, I am unsure how to change between these converters when the state of the checkbox changes.

My plan was to have a field "IValueConverter lengthConverter" on my ViewModel which I could set to one converter or the other, then in my XAML do ...="{Binding Converter={Binding Path=lengthConverter}}" - unfortunately this does not work since Converter is not a dependency property.

How can change the converter used by the data binding at runtime?

2
You should be able to use DependencyObject.GetBinding(DependencyProperty), e.g. myTextBlock.GetBinding(TextBlock.TextProperty) to get (and modify) the Binding object.Heinzi
Unfortunately, following the MVVM pattern means that code would need to live in the ViewModel - which has no reference to the view and thus cannot touch "myTextBlock".user200783

2 Answers

5
votes

Most of the time when using the MVVM methodology, you can do the formatting task in the VM classes. In your case, you could add a Format property to the VM class, and based on the value of the Format property, return a well formated string.

See this discussion for more information.

0
votes

If I may suggest a simple alternative solution: Create a small FormatMillimetresConverter in your ViewModel, whose UseMetric property is bound to the "metric" checkbox.