FocusLost when managing users [wpf]

The FocusLost event works correctly with WPF components. For User-Control, this is different:

if any control in User-Control is clicked or focused, FocusLost user control starts immediately! How can I stop this?

I could not solve this problem :(

+4
source share
2 answers

You can check IsKeyboardFocusWithin on a UserControl to determine if the UserControl object or any of its children has KeyBoard focus or not. There is also an IsKeyboardFocusWithinChanged event that you can use, just check if e.OldValue true and e.NewValue false in the event handler.

Edit
Here is an example of how you can make UserControl raise a routed event ( UserControlLostFocus ) when IsKeyboardFocusWithin turns false.

Used as

 <my:UserControl1 UserControlLostFocus="userControl11_UserControlLostFocus" ../> 

UserControl Example

 public partial class UserControl1 : UserControl { public static readonly RoutedEvent UserControlLostFocusEvent = EventManager.RegisterRoutedEvent("UserControlLostFocus", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UserControl1)); public event RoutedEventHandler UserControlLostFocus { add { AddHandler(UserControlLostFocusEvent, value); } remove { RemoveHandler(UserControlLostFocusEvent, value); } } public UserControl1() { InitializeComponent(); this.IsKeyboardFocusWithinChanged += UserControl1_IsKeyboardFocusWithinChanged; } void UserControl1_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e) { if ((bool)e.OldValue == true && (bool)e.NewValue == false) { RaiseEvent(new RoutedEventArgs(UserControl1.UserControlLostFocusEvent, this)); } } } 
+9
source

If you do not want something to catch fire, you can add this to the source .CS file behind the XAML control:

 protected override void OnLostFocus(RoutedEventArgs e) { e.Handled = true; } 
+1
source

All Articles