Binding Multiple Controls to One - Windows Phone

Binding Multiple Controls to One - Windows Phone

  • Comments 0

A co-worker of mines is building a price calculator app for Azure. He is an Azure specialist with no Window Phone development experience. He wanted to have multiple slider controls adjust the value of one textbox.  Originally I thought so simple, just to element binding to get the value on on control into the property of another control.

 1: <StackPanel x:Name="stackPanel">
 2:      <TextBox x:Name="TextboxControl" Height="70" Margin="0,0,0,0" TextWrapping="Wrap" Text="{Binding Value, ElementName=SliderControl, Mode=TwoWay}" VerticalAlignment="Top"/>
 3:      <Slider x:Name="SliderControl" Margin="0,0,0,0"/>
 4: /StackPanel>

Obviously, this is not what he needed. He needs to have multiple sliders control the value of one textbox. To get the results we wanted, I simply bind the textbox to a property that returns the “sum” of all other values. You can apply any equation you like.

The XAML is simple. All we need is to controls to be bounded (twoway) to a property in the view model like this:

 1: <StackPanel x:Name="stackPanel">
 2:     <TextBox x:Name="TextboxControl" Height="70" Margin="0,0,0,0" TextWrapping="Wrap" Text="{Binding Results}" VerticalAlignment="Top"/>
 3:     <Slider x:Name="SliderControl"  Value="{Binding Slider, Mode=TwoWay}" Margin="0,0,0,0"/>
 4:     <Slider x:Name="SliderControl1" Value="{Binding Slider1, Mode=TwoWay}" Margin="0,0,0,0"/>
 5:     <Slider x:Name="SliderControl2" Value="{Binding Slider2, Mode=TwoWay}" Margin="0,0,0,0"/>
 6:     <Slider x:Name="SliderControl3" Value="{Binding Slider3, Mode=TwoWay}" Margin="0,0,0,0"/>
 7:     <Slider x:Name="SliderControl4" Value="{Binding Slider4, Mode=TwoWay}" Margin="0,0,0,0"/>
 8: </StackPanel>

In the view model since we only care about the slider value change for the purpose of our calculation, INotifyPropertyChange for the Results Property like this:

 1: public double Slider4
 2: {
 3:     get { return _slider4; }
 4:     set
 5:     {
 6:         if (_slider4 == value)
 7:             return;
 8:         _slider4 = value;
 9:         NotifyPropertyChanged("Results");
 10:     }
 11: }
 12:         
 13: public double Results
 14: {
 15:     get { return (Slider + Slider1 + Slider2 + Slider3+ Slider4); }
 16: }

Notice that for the Results property which is bounded to the textbox, I simply return the calculation needed.

That’s it simple but useful. Download the sample here