我有一个数据绑定的文本框在我的应用程序,像这样:(类型的 Heightdecimal?)

<TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged, 
                        ValidatesOnExceptions=True, 
                        Converter={StaticResource NullConverter}}" />

public class NullableConverter : IValueConverter {
    public object Convert(object o, Type type, object parameter, CultureInfo culture) {
        return o;
    }

    public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
        if (o as string == null || (o as string).Trim() == string.Empty)
            return null;
        return o;
    }
}

构成这种方式,任何非空串不可转换到小数点的结果验证错误,这将立即突出的文本框。然而,该文本仍然可以失去的重点和仍然存在的无效状态。什么我想要做的是:

  1. 不允许文本框失去重点,直到它包含一个有效的价值。
  2. 恢复的价值的文本的最后一个有效的价值。

什么是最好的方式做到这一点?

更新:

我已经找到一个办法做到#2.我不爱它,但是它的工作:

private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
    var box = sender as TextBox;
    var binding = box.GetBindingExpression(TextBox.TextProperty);
    if (binding.HasError)
        binding.UpdateTarget();
}

任何人都不会知道如何做到这一点好吗?(或做#1.)

有帮助吗?

解决方案

你能力的键盘重点,留在 TextBox 通过处理的 PreviewLostKeyBoardFocus 像这样的事件:

 <TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" /> 

 private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
     e.Handled = true;
 }

其他提示

它听起来到我,你会需要处理两个事件:

GotFocus:将触发时,文本框收益的焦点。你可以储存的初始价值的框。

LostFocus:将触发时,文本框失去了焦点。在这一点上你可以做你的验证,并决定如果你想滚回或没有。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top