Hold Focus if Control has Vaidation.HasError

Dec 17, 2008 at 7:41 PM
Hi,

I want to achive that a Textbox with Validation.HasError = true does not releases his focus, nor by mouse, neither by keyboard:

// for Mouse
this.tbContactName.LostFocus += new RoutedEventHandler(tbContactName_LostFocus);
// for Keyboard, but fires before Validation
this.tbContactName.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tbContactName_LostKeyboardFocus);


void tbContactName_LostFocus(object sender, RoutedEventArgs e)
{
// DevelopersDex
TextBox tb = e.Source as TextBox;
if (Validation.GetHasError(tb))
     tb.Focus();
}

void tbContactName_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{ // The same code like in tbContactName_LostFocus() }

My questions:
1.) Is it the right approach to use this TWO Events?
2.) The LostKeyboardFocus fires before validation. But I need it: if I remove it, the LostFocus() rund into an endlees loop -> Stack overflow :-(

-christoph
Coordinator
Jan 7, 2009 at 2:02 PM
If you take that approach of using these two events, for the LostKeyboardFocus you can wrap the code inside in a Dispatcher.BeginInvoke and set the priority lower so the validation fires.  I haven't tested that out though.

Another approach is to not police the user based on focus of a textbox but more based on what is enabled.  I have an example here, http://blogs.msdn.com/vinsibal/archive/2008/12/18/wpf-datagrid-sample-locking-input-to-the-row-being-edited.aspx, which locks input to the row being edited.  Maybe you can try the same idea when a cell is in error.
Jan 8, 2009 at 8:32 PM
Hi vinsibal,

thanks for your advice!

>wrap the code inside in a Dispatcher.BeginInvoke and set the priority lower so the validation fires.

Can you give me some code, how to do this? I'm a deverloper since many years, but a newbee in WPF/c# ;-)
Coordinator
Jan 13, 2009 at 2:47 AM
Here is an example:

Dispatcher

 

.CurrentDispatcher.BeginInvoke(new DispatcherOperationCallback((param) => { /* code goes here*/}), DispatcherPriority.Background, new object[] { null } /* parameter */);

 

Jan 17, 2009 at 10:21 PM
Thanks, but The LostKeyboardFocus alway fires before validation :-(
This is my code, ist there an error?

 void tbContactName_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new DispatcherOperationCallback((param) =>
            {
                TextBox tb = e.Source as TextBox;
                MessageBox.Show("LostKeyboardFocus");
                if (Validation.GetHasError(tb))
                    tb.Focus();
                return null;
            }
            ), DispatcherPriority.Background, new object[] { null });
        }