简体   繁体   English

WPF:具有最小值的文本框和滑块

[英]WPF: Textbox + Slider with min values

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. 问题是,如果我开始在文本框中输入超出最小值的值,则这些值会自动传输到最小值。 eg 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. 例如,如果我将最小值设置为4,并且我想输入12,则一旦按1,它已经在文本框中更改为4,而我不能输入12,而是42。如果我开始输入4或5(例如42或51等)就可以了。

Is there a way to defer this check of min until after the user has pressed enter ? 有没有办法推迟对min的检查,直到用户按下enter键?

Here's the XAML: 这是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>

Set the UpdateSourceTrigger property to LostFocus and press TAB : UpdateSourceTrigger属性设置为LostFocus并按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: 或按ENTER键并按如下方式处理PreviewKeyDown事件:

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: 或者,您可以按照@Clemens的建议显式更新source属性:

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM