开发者

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-Cont开发者_Python百科rol'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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜