Why does the LostFocus event get called at different times? - c#

In reference to this MSDN page (or any related page on the matter), it states that:
When you change the focus by using the keyboard, focus events occur in
the following order:
Enter
GotFocus
Leave
Validating
Validated
LostFocus
However, when you use the mouse to raise events, the order changes!
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
Wouldn't this make the chain of events completely different? My interpretation here is that the keyboard chain ensures everything is in working order, then raises the LostFocus event. Yet, the mouse events seem to raise it before validating for some reason. Why is that?

As noted above:
In the MSDN article you linked worded strong enough? Never use LostFocus, only Leave.
The keyboard navigation must be in this order in order to apply the validations. Those are intended to react to them in order to validate any input strings.

The best example I can think of is the e.Cancel aspect in validation. Using the keyboard for navigation is usually a control to control type of navigation (including child and parent controls). Using the mouse for form navigation does not always result in a control being selected. For example closing a form or simply click outside of the control (i.e. re-positioning the form). It is not always desirable to have the validation occur when a mouse click occurs outside a control. Hope that helps.

Related

WPF Validate/Setter calls in wrong order

I have a textbox inside a TabControl. The textbox binding has UpdateSourceTrigger=LostFocus. The textbox uses Attribute based validation from the data model. This validation is working correctly.
In the TabControl.SelectedItemChanged event I call modelObject.Validate() and prevent the switch to a different tab if an error occurs.
The problem I have is that the order of execution is backwards. The validate call occurs before the property setter. In the case of an invalid field I am able to switch away from the tab even though an error has been detected.
How do I get the order or these events ordered properly?
Is there a way to cancel TabControl.Items.CurrentChanging?
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d8ac2677-b760-4388-a797-b39db84a7e0f/how-to-cancel-tabcontrolselectionchanged?forum=wpf
Seems to work by subscribing the CurrentChanging event. Can cancel tab changing action by setting the CurrentChangingEventArgs Cancel to true
WPF is definitely incorrect here. However, the fix is really simple.
In the SelectionChanged event handler call {whatever your tabcontrol is called}.Focus(). This immediately forces the lostfocus event for the textbox (which forces the setter to be fired) and solves the problem.

WPF - Common event fired for value changed

Ok. This seems like an incredibly basic use case but fore some reason I am having an issue finding a common solution across control types.
Heres the use case:
A form is presented to the user with any editable controls. (Text box, combo, grid etc.).
The user edits a value in the control and tabs out.
Expectation is that I can wire to an event like Lost Focus and do "foo" with the changed value.
The user then gives focus back to the control and tabs out without making an edit.
Expectation is that whatever event I am wired to I can check if the value has been changed.
Is there one common event across controls that will only fire when the user has finished editing( such as tab out or enter ) and allow me to check previous state vs. current state?
Jason, you may want to look into Binding and DependencyProperties in WPF instead of tracking events in your form. You would bind a class to your form which exposes properties to be changed. Using DependancyProperties a single event is fired called "PropertyChanged".
Unfortunately is is a broad topic, but you will really get the full benefit of the WPF programming model. Searches on "dependency properties in wpf" will give you some good examples.
I think maybe this is Focus issue. There exist two different focus types: keyboard focus and logical focus. The the control that has keyboard focus is the one that has the caret, in what the user press a key and the control process that input. The a control may have the logical focus but not having the keyboard focus. Please check this in the MSDN article "Input Overview". About the other question, maybe you could process the TabControl.SelectedItemChanged for taking the event when a tab item selection changed.
Hope this is helpful to you...
What you may be interested in is implementing INotifyPropertyChanging (not just INotifyPropertyChanged).
As noted in the answer of this question, the INotifyPropertyChangING does not prevent you from changing a value, but to detect WHEN something DOES change, and what it's new value is going to be.
Hope it helps in your solution needs.
As the previous answers suggested, you would be better off by implementing a view - viewmodel structure, with your viewmodel having implemented INotifyPropertyChanged, and thus allowing you to bind to properties that will announce their changes to the UI.
If you don't want to do this, you can eventually subscribe on your input elements to the PreviewKeyUp event, check if the Tab key has been pressed and proceed from there.

What is a good way to base the enabled state of the OK button in a dialog on valid control entries

Even if I associate the button with a class derived from ICommand, I am still left with figuring out how the button should trigger the CanExecute method and refresh its enabled state. I do know about the CanExecuteChanged event for which a button with an associated command registers, but see the following paragraph for why this is troublesome.
On a plain old dialog consisting of some 10-15 controls, it seems haphazard to have to process every change notification for every single one of those controls, triggering the CanExecuteChanged event on the button's command, causing the button's enabled state to be affected by the CanExecute method's return value. Even stating what needs to be done in the last sentence was quite cumbersome.
There must be a better way of coding a WPF dialog, so that the confirmation button (e.g., OK) is grayed out until all controls have valid information and is enabled at that point in time (i.e., when all controls are properly filled in). Sample code, ideas and pointers to articles would be immensely appreciated.
Thanks
I don't see anything haphazard here. Since your condition is "all controls have valid information", this can occur after any control is edited, and therefore you need to listen to change notifications from all controls.
On a plain old dialog consisting of some 10-15 controls, it seems
haphazard to have to process every change notification for every
single one of those controls,
I don't think so. Every Textbox, checkbox changed event is handled by the same handler, say SetState(), which calculates the overall state of the dialog. Every time a control is edited, the entire state is recalculated.
until all controls have valid information
Then that object would have a boolean property EnableOKButton, let's say, which is set according to the updated state. Then that property is bound to the button's Enabled property so it automagically changes - without dealing with extraneous events.

TextBox.SelectAll() does not work with TAB

I am using maskedTextBox.SelectAll() to highlight the text in the MaskedTextBox in the Enter and MouseDown events.
It works when I use the mouse, but I go to that textbox by pressing the Tab key, it does not work.
What am I missing here?
Have you tried the GotFocus event?
When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:
It then goes on to list the events that are fired. It looks like this fires when the mouse is used so you might only need this handler.

Handling selected objects on the GUI in WPF

I've built several user controls in WPF and they all get added to a canvas. I want to add a behaviour that keep tracks of the currently selected usercontrol. A usercontrol should be selected when:
The mouse clicks on it;
when it recieve focus;
when either of the two above happens to a subcontrol of the usercontrol.
Is there any way to handle this purely by using the focus mechanism of WPF or will I need to take care of this myself with assistance of the focus classes?
I've read up upon the new way of handling focus in WPF, and the problem I'm facing is that the keyboard focus determines what the currently selected object is, but some parts of the my control can't recieve keyboard focus so even though these parts are clicked, the usercontrol doesn't recieve focus.
I'm looking for advice on how to implement this feature and how much I could/should rely on the focus mecanisms. Ultimatively I wouldn't mind if only a single object could be selected, but if it's easily extendable to multi-select then I wouldn't mind this either.
Just to clarify, I know I could build this manually by handling a lot of events and keeping track of states, but I was just hoping an easier approach was available.
Combine UIElement.IsKeyboardFocusWithin with a PreviewMouseDown handler:
When PreviewMouseDown is called, set a flag and schedule callback using Dispatcher.BeginInvoke at DispatcherPriority.Input to set focus to the UserControl if the flag is still set.
Set a handler for UIElement.IsKeyboardFocusWithin property changes in your UserControl. When the handler fires, clear the flag.
The idea here is that if you click anywhere on the UserControl and keyboard focus does not result in the focus being moved into the UserControl, force it into the UserControl.
FYI, here's roughtly what step 1 looks like in code:
public override OnPreviewMouseDown(MouseButtonEventArgs e)
{
_mouseClickedButNoFocus = true;
Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
{
if(_mouseClickedButNoFocus)
Focus();
});
}
You could use the UIElement.IsKeyboardFocusWithin property, which is true when the UIElement or one of its children has keyboard focus. It is a dependency property, so you can easily use it for a trigger in a style
You can set the logical focus to the control when any of the child gets the keyboard focus using FocusManager.IsFocusScope="True". Setting the keyboard focus to the control or trying to do will eat the keys for the child controls.
You can use UIElement.IsKeyboardFocusWithin to set the focus of the control if any of the children has focus.
You can read this article which I think describes the difference between Logical and Keyboard focus quite well:
http://www.pluralsight.com/community/blogs/eburke/archive/2009/03/18/why-is-focus-in-wpf-so-tricky-managing-and-understanding-focus-in-a-wpf-application.aspx

Categories