WPF - Remove focus when clicking outside of a textbox

前端 未结 13 2145
粉色の甜心
粉色の甜心 2020-12-02 19:11

I have some textboxes where I would like focus to behave a little differently than normal for a WPF application. Basically, I would like them to behave more like a textbox b

13条回答
  •  渐次进展
    2020-12-02 19:20

    To avoid code behind you can use this Behavior The behavior

     public class ClearFocusOnClickBehavior : Behavior
     {
        protected override void OnAttached()
        {
            AssociatedObject.MouseDown += AssociatedObject_MouseDown;
            base.OnAttached();
        }
    
        private static void AssociatedObject_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Keyboard.ClearFocus();
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.MouseDown -= AssociatedObject_MouseDown;
        }
    }
    

    Useing in XAML:

    On any element outside the text box that you want him to clear the focus on click add:

        
            
        
    

提交回复
热议问题