WPF: Binding slider and textbox

This entry is part 23 of 54 in the series Learn WPF

When we move the slider, we can have the text in the TextBox updated accordingly.

Using a two-way mode, when we update the value in the TextBox, we can have the slider to move according to the value in the TextBox too.

In the previous example, when we move the slider, the font size changes accordingly.  This behaviour is actually controlled by UpdateSourceTrigger property.  As we did not specify its value, it is in its default state which then depends on the source that it is bound to.

The default value for most properties is PropertyChanged, while the Text property has a default value of LostFocus.

The example below best illustrate the LostFocus property of a slider which in this case is the source.  The TextBox is the target.

<Window x:Class="SliderName.MainWindow"
        Title="MainWindow" Height="350" Width="525">
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="100" />
        <TextBox Text="{Binding Path=Value, ElementName=slider, UpdateSourceTrigger=LostFocus, Mode=TwoWay}" Grid.Row="0" FontSize="20" MaxWidth="50"/>
        <Slider x:Name="slider" Grid.Row="1" Minimum="10" Maximum="80" Value="30" IsSnapToTickEnabled="True"/>


If you click on the slider and move along the line, the value in the textbox will change accordingly.

In this example, we also have a two-way mode binding and a LostFucus value in UpdateSourceTrigger.  If you change the value in the TextBox and click the mouse pointer not on the slider but right below the slider simulating a lost focus click, the slider will move depending on the value in the TextBox.

Series Navigation<< WPF: Data binding with slider
WPF: Binding to a single object >>