This mini-tutorial extends the work done in number 6, adding a slider and a text block bound to the value of the slider, through element binding – that is, the binding of one element’s value (in this case the TextBlock) to a value in a second element (in this case the slider).
(If you don’t have the code from the previous example you can just create a new Windows Phone application and add the controls discussed here into the first row rather than into row six.)
Open a new application or, even better, open the previous application. If you open the previous application, change the row for the Next button to row 7 and do this work on row 6.
Adding the Slider
Drag a slider from the toolbox into the first column. There are a number of settings that are important in a slider including:
- Minimum
- Maximum
- Value
- LargeChange
- SmallChange
<Slider x:Name="Likability" Grid.Row="5" Grid.Column="0" BorderBrush="White" BorderThickness="1" Background="White" Foreground="Blue" LargeChange="10" SmallChange="1" Minimum="0" Width="199" Maximum="100" Value="50" Height="90" />
Minimum and Maximum set the range of the slider. In this case, since I’m using percentage, I’ve set them to 0 and 100 respectively.
Value is the current value of the slider, and will be
Minimum <= value <= Maximum
LargeChange and SmallChange are used much as they are in scrollbars; they indicate what clicking into the slider will do and what using another control (perhaps arrows) to incrementally move the slider will do respectively.
Setting up the Text Blocks
In the right hand column, we’ll use three TextBlocks; the first and third as fixed labels (with the values Likeability: and % respectively) and the middle text block displaying a numeric representation of the value of the slider.
To accomplish this, we bind the Text value property of the middle TextBlock to the Value property of the slider, identifying which element we’re binding to with the keyword ElementName.
<StackPanel x:Name="LikabilityPercentStackPanel" Grid.Row="5" Grid.Column="1" Orientation="Horizontal"> <TextBlock Text="Likeability: " HorizontalAlignment="Left" VerticalAlignment="Center" Margin="20,0,5,0" /> <TextBlock x:Name="SliderValue" Text="{Binding Value, ElementName=Likability}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/> <TextBlock Text="%" HorizontalAlignment="Left" VerticalAlignment="Center" />
As the Slider is adjusted, the value in the TextBlock is updated instantly.
Weird. I tried this and the slider on the emulator started giving me values in decimal fractions even when small change was 1 on the slider.
Siddharth, to get round this change the string format on the binding like so:
Text="{Binding ElementName=Likability, Path=Value, StringFormat=\{0:F0\}}"
Thank you. Just had the problem :p
Didn’t think it was just a StringFormat issue. Nice 🙂