0

I have a textbox binded to a slider, and the slider has minimum value set.

The problem is that if I start entering the values in the textbox that are out of the min - they are automatically transferred to the min. e.g. if I set the min to 4, and I want to type 12, once I press 1, it's already changed to 4 in the textbox, and I can't enter 12, instead it will be 42. If I start typing something with 4 or 5 (say 42, or 51, etc.) it will be ok.

Is there a way to defer this check of min until after the user has pressed enter ?

Here's the XAML:

<TextBox Text="{Binding ElementName=maxValue, Path=Value, UpdateSourceTrigger=PropertyChanged}" TextAlignment="Center" VerticalContentAlignment="Center" Width="30" Height="25" BorderBrush="Transparent"></TextBox>
<Slider Value="{Binding TotalSize}" Maximum="{Binding MaxMaxBackupSize}" Minimum="{Binding MinBackupSize}" TickPlacement="BottomRight" TickFrequency="2" IsSnapToTickEnabled="True" Name="maxValue"></Slider>
Maverick Meerkat
  • 5,737
  • 3
  • 47
  • 66

1 Answers1

1

Set the UpdateSourceTrigger property to LostFocus and press TAB:

<TextBox Text="{Binding ElementName=maxValue, Path=Value, UpdateSourceTrigger=LostFocus}" TextAlignment="Center" VerticalContentAlignment="Center" Width="30" Height="25" BorderBrush="Transparent"></TextBox>

Or press ENTER and handle the PreviewKeyDown event like this:

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        e.Handled = true;
        TextBox textBox = sender as TextBox;
        textBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}

Or you could just explicitly update the source property as suggested by @Clemens:

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        e.Handled = true;
        TextBox textBox = sender as TextBox;
        BindingExpression be = textBox.GetBindingExpression(TextBox.TextProperty);
        be.UpdateSource();
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88