Psytronic
Psytronic

Reputation: 6113

Xaml binding for radio/checkbox to toggle between imperial/metric

Pretty much as the title states, I'm grabbing some values from a Db, which are all in Km, but I want to implement a converter which I can toggle between Miles or Kilometers, and want to bind which is displayed to either a checkbox, or a radio button group, whichever is easiest (Radio would be preferred).

I'm thinking I can just use an IValueConverter rather than an IMultiValueConverter, and the Convert/ConvertBack methods, as the default will be Kilometers, but I don't know how to call the ConvertBack method. Or I could pass true/false as the ConverterParameter depending on whether I want Km/Miles displayed.

But either way I'm not sure how to hook up the Xaml Binding on either method (I know how to do a standard value converter binding, but not the extra flumff needed.

Any hints appreciated.

<StackPanel Grid.Row="0" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Right">
    <RadioButton Content="Km" GroupName="rdBtnGrpValue" IsChecked="True" />
    <RadioButton Content="Miles" GroupName="rdBtnGrpValue" />
</StackPanel>

And:

<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="1" Text="{Binding EquatorialCircumference, Converter={StaticResource KmMiConv}, StringFormat='{}{0:0,0.0}'}" />

Upvotes: 1

Views: 608

Answers (1)

Jay
Jay

Reputation: 57919

If you are using the MVVM pattern, and are using a view-model as your DataContext, you could use a Mode=TwoWay binding between the RadioButtons and a boolean property in the view-model, something like bool ConvertToImperial { get; set; }.

Your actual conversion can occur in the getter for the EquatorialCircumference property. If ConvertToImperial is true, return the value in miles, otherwise return the value in kilometres.

Then, for the TextBox, you can simply bind it to the EquatorialCircumference property, and the value displayed will be in the selected unit.

You will, however, need to raise a property change notification for any properties whose values are affected by a change in units.

Upvotes: 2

Related Questions