icaptan
icaptan

Reputation: 1535

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

Upvotes: 5

Views: 7972

Answers (2)

Alex Curtis
Alex Curtis

Reputation: 5767

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;
}

Upvotes: 1

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84684

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));
        }
    }
}

Upvotes: 13

Related Questions