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 dont want anything to fire on focus being lost you can add this to the source .CS file behind the XAML User Control:
protected override void OnLostFocus(RoutedEventArgs e)
{
e.Handled = true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.