Bob
Bob

Reputation: 4386

WPF binding: Doing a temperature converter app

I'm doing a little app that basically has 2 text boxes. You'll enter Fahrenheit into TextBoxA and Celsius into TextBoxB.

As the text changes in TextBoxA I want the equivalent Celsius value to be displayed in TextBoxB and vice versa.

I can come up with a solution pretty easy for this but i'm trying to be a little clever.

Is there a way to do it all in Xaml except for a Convert class that does the maths? So basically I want the TextChanged event of one textBox to pass in it's value into a Converter class that is evaluated and sent to the other TextBox and visa versa.

Anyone know how I can achieve this ... and if it's possible at all?

Upvotes: 0

Views: 2285

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178700

<TextBox x:Name="CelcuiusTextBox" Text="{Binding Text, ElementName=FahrenheitTextBox, Converter={StaticResource FahrenheitToCelciusConverter}}"/>
<TextBox x:Name="FahrenheitTextBox" Text="{Binding Text, ElementName=CelciusTextBox, Converter={StaticResource CelciusToFahrenheitConverter}}"/>

Assumes the existence of two distinct converters. Of course, you could write a single converter that can be put in a different mode to convert either from or to celcius.

Upvotes: 1

Jay
Jay

Reputation: 57939

<TextBox x:Name="Celsius" />
<Textbox x:Name="Fahrenheit" Text="{Binding Text, ElementName=Celsius, Mode=TwoWay, Converter={StaticResource CelsiusToFahrenheitConverter}}" />

When you update C, F will get the value and convert it. When you update F, it will convert back to C and push the value to the Celcius textbox.

Upvotes: 3

Related Questions