Koopakiller
Koopakiller

Reputation: 2883

Set Focus in VisualStatemanager

I write a custom control and want to set the focus on a control in case a VisualState goes active.

The control is a kind of ComboBox with a search box in the drop down popup. When I open it, the Opened Visual State goes active and the search box should be focused. Besides a dependency property bool IsDropDownOpen will be true.

PS: It's an Windows 10 UWP project.

Upvotes: 0

Views: 584

Answers (2)

Koopakiller
Koopakiller

Reputation: 2883

Not my favorite solution, but a workaround without accessing the TextBox from code behind.

I implemented an attached property which sets the focus to a control in case the property is set to true.

public class FocusHelper : DependencyObject
{
    #region Attached Properties

    public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusHelper), new PropertyMetadata(default(bool), OnIsFocusedChanged));

    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }

    #endregion

    #region Methods

    public static void OnIsFocusedChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
    {
        var ctrl = s as Control;
        if (ctrl == null)
        {
            throw new ArgumentException();
        }

        if ((bool)e.NewValue)
        {
            ctrl.Focus(FocusState.Keyboard);
        }
    }

    #endregion
}

So I can bind this property to my IsDropDownOpen property. So every time I open the drop down, the TextBox will get the focus.

<TextBox helper:FocusHelper.IsFocused="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" ...

Upvotes: 1

Mykyta Bondarenko
Mykyta Bondarenko

Reputation: 552

Sorry, but you can set focus only programmatically, not by visual state :(

Upvotes: 1

Related Questions