문제

내 응용 프로그램에는 다음과 같은 데이터 바인딩된 TextBox가 있습니다.(종류 Height ~이다 decimal?)

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

이러한 방식으로 구성하면 10진수로 변환할 수 없는 비어 있지 않은 문자열은 텍스트 상자를 즉시 ​​강조 표시하는 유효성 검사 오류가 발생합니다.그러나 TextBox는 여전히 포커스를 잃고 잘못된 상태로 남아 있을 수 있습니다.내가 하고 싶은 일은 다음 중 하나입니다.

  1. 유효한 값이 포함될 때까지 TextBox가 포커스를 잃지 않도록 하십시오.
  2. TextBox의 값을 마지막 유효한 값으로 되돌립니다.

이를 수행하는 가장 좋은 방법은 무엇입니까?

업데이트:

#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;
 }

다른 팁

제 생각에는 두 가지 이벤트를 처리하고 싶은 것 같습니다.

초점을 맞췄습니다:텍스트 상자에 초점이 맞춰지면 트리거됩니다.상자의 초기값을 저장할 수 있습니다.

잃어버린 초점:텍스트 상자가 포커스를 잃을 때 트리거됩니다.이 시점에서 유효성 검사를 수행하고 롤백할지 여부를 결정할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top