Strong Validation in WPF

I have a databound TextBox in my application like so: (The type of Height is decimal?)

<TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged, 
                        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;

Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:

  1. Not allow the TextBox to lose focus until it contains a valid value.
  2. Revert the value in the TextBox to the last valid value.

What is the best way to do this?


I've found a way to do #2. I don't love it, but it works:

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

Does anyone know how to do this better? (Or do #1.)


You can force the keyboard focus to stay on the TextBox by handling the PreviewLostKeyBoardFocus event like this:

 <TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" /> 

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

Need Your Help

Declaratively access page properties data binding inside repeater data-binding webforms repeater

I have a public property on an ASP.NET Forms page. I can access this page property declaratively with the following code:

Java wait() not Throwing InterruptedException

java concurrency synchronization wait notify

I have an object on thread A that is calling wait() while another object on thread B does some work then calls thread A's object's notify(). Thread A then performs some post-processing.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.