WPF and MVVM: changing data binding converter at run time

I am using WPF and the MVVM pattern in my user interface. In my ViewModel, I have a list containing the distances in millimeters that I show in the ListView by binding ListView.ItemsSource to the list. However, I would like the displayed values ​​to use a more natural unit - meters or feet depending on the state of the metric.

I wrote some simple classes: MillimetresToMetresConverter and MillimetresToFeetConverter, both of which implement IValueConverter. Although I can set the Converter property when binding data to one or the other, I'm not sure how to change these transformations when the state of the checkbox changes.

My plan was to have a "IValueConverter lengthConverter" field on my ViewModel that I could install on one converter or another, and then in my XAML do ...="{Binding Converter={Binding Path=lengthConverter}}" - Unfortunately, this does not work, because the converter is not a dependency property.

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

+6
data-binding wpf mvvm ivalueconverter
source share
2 answers

In most cases, when using the MVVM methodology, you can perform the formatting task in VM classes. In your case, you can add the Format property to the VM class and return a correctly formed string based on the value of the Format property.

See this discussion for more details.

+5
source share

If I can offer a simple alternative solution: create a small FormatMillimetresConverter in your ViewModel, whose UseMetric property is associated with the label "metric".

0
source share

All Articles