Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus textbox in WP7 using MVVM?

The question has been asked a couple of times, unfortunately the answers only apply to WPF. Anyone know how to accomplish this in silverlight? Basically I need to focus on a certain textbox from code.

like image 402
Edward Avatar asked May 12 '11 18:05

Edward


1 Answers

I've used this approach successfully

http://caliburnmicro.codeplex.com/discussions/222892?ProjectName=caliburnmicro

public class FocusBehavior : Behavior<Control>
    {

        protected override void OnAttached()
        {
            AssociatedObject.GotFocus += (sender, args) => IsFocused = true;
            AssociatedObject.LostFocus += (sender, a) => IsFocused = false;
            AssociatedObject.Loaded += (o, a) => { if (HasInitialFocus || IsFocused) AssociatedObject.Focus(); };

            base.OnAttached();
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.Register(
                "IsFocused",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, (d, e) => { if ((bool)e.NewValue) ((FocusBehavior)d).AssociatedObject.Focus(); }));

        public bool IsFocused
        {
            get { return (bool)GetValue(IsFocusedProperty); }
            set { SetValue(IsFocusedProperty, value); }
        }

        public static readonly DependencyProperty HasInitialFocusProperty =
            DependencyProperty.Register(
                "HasInitialFocus",
                typeof(bool),
                typeof(FocusBehavior),
                new PropertyMetadata(false, null));

        public bool HasInitialFocus
        {
            get { return (bool)GetValue(HasInitialFocusProperty); }
            set { SetValue(HasInitialFocusProperty, value); }
        }
    }


<TextBox x:Name="UserName" Style="{StaticResource LoginTextBox}">
  <i:Interaction.Behaviors>
    <localBehaviors:FocusBehavior HasInitialFocus="True" 
      IsFocused="{Binding UserNameIsFocused, Mode=TwoWay}"/>
  </i:Interaction.Behaviors>
</TextBox>
like image 144
kenwarner Avatar answered Oct 13 '22 20:10

kenwarner