Reputation: 167
I have three Controls:a slider, a button, and a textbox. And what I want to achieve is that When I drag the slider to change it's value,the content of textbox changes.The content of textbox is the value of the slider.However, when I click the button, the value of the slider adds 1 but the content of textbox doesn't change.The textbox shows the value of the Slider.But it changes it's content only when I change the value of slider by dragging the slider. So how can I make this work in code?
Upvotes: 1
Views: 1519
Reputation: 167
Here is where I found the solution.
And my code is: In Xaml:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Slider Name="mySlider" ValueChanged="mySlider_ValueChanged" Thumb.DragStarted ="mySlider_DragStarted"
Thumb.DragCompleted ="mySlider_DragCompleted"/>
<TextBox Name="tboxValue" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Text="0"
Grid.Row="1"/>
<Button Content="Add" Name="btnAdd" Click="btnAdd_Click" Grid.Row="2"/>
</Grid>
In code:
private bool isdragging = false;
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
mySlider.Value += 1;
}
private void mySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (isdragging)
tboxValue.Text = mySlider.Value.ToString();
}
private void mySlider_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
{
isdragging = true;
}
private void mySlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
isdragging = false;
}
It works perfectly for me.
Upvotes: 1
Reputation: 334
Bind the textbox TEXT property to the slider's VALUE property using Element Name
<Slider x:Name="Slider"></Slider>
<TextBox x:Name="SliderValue" Text="{Binding ElementName=Slider, Path=Value}"></TextBox>
The textbox will auto update when the slider value change.
Upvotes: 0