2017-08-15 88 views
0

我有一个绑定到滑块的文本框,并且滑块具有最小值设置。WPF:带最小值的文本框+滑块

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

有没有办法推迟这种检查分钟,直到用户按下输入后?

这里的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> 
+0

尝试添加'模式= OneWayToSource'在文本结合 – ASh

+0

@ASh但后来它不更新滑块 –

+1

这可能是有帮助:https://stackoverflow.com/a/564659/1136211。然后你应该删除'UpdateSourceTrigger = PropertyChanged'。 – Clemens

回答

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

而不是更改关键事件处理程序中的焦点,而是通过BindingExpression.UpdateSource更好地显式更新源属性。 – Clemens

+1

@元素:好点。我将这添加到我的答案中。 – mm8

+0

谢谢你们,非常感谢 –