【问题标题】:How to focus textbox in WP7 using MVVM?如何使用 MVVM 在 WP7 中聚焦文本框?
【发布时间】:2011-08-24 08:56:08
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    我已经成功地使用了这种方法

    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>
    

    【讨论】:

    • 谢谢!效果很好。还有一种方法可以通过这些绑定使文本框失去焦点吗? (无需关注另一个文本框)
    • 解决了我的问题。我在我的 TextBox 的 isEnabled 上使用绑定。禁用 + 启用将使文本框失去焦点。看起来像一个黑客,但没有找到其他方法:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多