如何使用MVVM在WP7中关注文本框?

时间:2011-05-12 18:34:20

标签: c# silverlight windows-phone-7 mvvm mvvm-light

这个问题已被问过几次,不幸的是答案只适用于WPF。任何人都知道如何在silverlight中实现这一目标?基本上我需要专注于代码中的某个文本框。

1 个答案:

答案 0 :(得分:11)

我已成功使用此方法

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>