Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FocusLost at User Control [wpf]

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 :(

like image 914
icaptan Avatar asked Aug 18 '11 16:08

icaptan


1 Answers

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));
        }
    }
}
like image 146
Fredrik Hedblad Avatar answered Sep 23 '22 23:09

Fredrik Hedblad