Set focus on TextBox in WPF from view model

后端 未结 21 2270
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:21

I have a TextBox and a Button in my view.

Now I am checking a condition upon button click and if the condition turns out to be false, displ

21条回答
  •  太阳男子
    2020-11-22 06:40

    This is an old thread, but there doesn't seem to be an answer with code that addresses the issues with Anavanka's accepted answer: it doesn't work if you set the property in the viewmodel to false, or if you set your property to true, the user manually clicks on something else, and then you set it to true again. I couldn't get Zamotic's solution to work reliably in these cases either.

    Pulling together some of the discussions above gives me the code below which does address these issues I think:

    public static class FocusExtension
    {
        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }
    
        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }
    
        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached(
             "IsFocused", typeof(bool), typeof(FocusExtension),
             new UIPropertyMetadata(false, null, OnCoerceValue));
    
        private static object OnCoerceValue(DependencyObject d, object baseValue)
        {
            if ((bool)baseValue)
                ((UIElement)d).Focus();
            else if (((UIElement) d).IsFocused)
                Keyboard.ClearFocus();
            return ((bool)baseValue);
        }
    }
    

    Having said that, this is still complex for something that can be done in one line in codebehind, and CoerceValue isn't really meant to be used in this way, so maybe codebehind is the way to go.

提交回复
热议问题