FocusLost event is working on WPF's components properly For User-Controls it is different:
if any control in the User-Control is clicked or focused, the User-Control's FocusLost is fired immediately ! How can I hinder it ?
I could not solve this problem :(
You can check IsKeyboardFocusWithin
on the UserControl
to determine if the UserControl
or any of its children has the KeyBoard focus or not. There is also the event IsKeyboardFocusWithinChanged
which you can use, just check if e.OldValue
is true
and e.NewValue
is false
in the event handler.
Edit.
Here is an example of how you could make the UserControl
raise a routed event (UserControlLostFocus
) when IsKeyboardFocusWithin
turns to false.
Useable like
<my:UserControl1 UserControlLostFocus="userControl11_UserControlLostFocus"
../>
Sample UserControl
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));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With