【问题标题】:WPF: Textbox + Slider with min valuesWPF:具有最小值的文本框 + 滑块
【发布时间】:2017-08-15 09:22:46
【问题描述】:

我有一个绑定到滑块的文本框,并且滑块设置了最小值。

问题是,如果我开始在文本框中输入超出最小值的值 - 它们会自动转移到最小值。例如如果我将最小值设置为 4,并且我想输入 12,一旦我按下 1,它已经在文本框中更改为 4,我不能输入 12,而是输入 42。如果我开始用 4 输入一些东西或 5(比如 42 或 51 等)就可以了。

有没有办法将这个 min 检查推迟到用户按下 enter 之后?

这是 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>

【问题讨论】:

  • 尝试在文本绑定中添加Mode=OneWayToSource
  • @ASh 但它不会更新滑块
  • 这可能会有所帮助:stackoverflow.com/a/564659/1136211。然后,您还应该删除 UpdateSourceTrigger=PropertyChanged

标签: c# wpf textbox slider


【解决方案1】:

UpdateSourceTrigger 属性设置为LostFocus 并按TAB

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

或按 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));
    }
}

或者您可以按照@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();
    }
}

【讨论】:

  • 与其在关键事件处理程序中更改焦点,不如通过 BindingExpression.UpdateSource 显式更新源属性。
  • 谢谢大家,非常感谢
猜你喜欢
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
相关资源
最近更新 更多