c# - 如何使用 MVVM 在 WP7 中聚焦文本框?

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

该问题已被问过几次,不幸的是答案仅适用于 WPF。任何人都知道如何在 silverlight 中完成此操作?基本上我需要关注代码中的某个文本框。

最佳答案

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

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>

关于c# - 如何使用 MVVM 在 WP7 中聚焦文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5982698/

相关文章:

c# - 将 appsettings.json 发布到不同的环境

c# - fxcop 是提高代码质量的有值(value)/有效的工具吗?

c# - 为什么我的 C# 代码中出现 "The name Regex does not exist in the current context"?

c# - PHP 数组到 C# 字符串

c# - 使wcf数据服务生成具有虚拟属性的实体

C# 预处理器 - 为 XAML 设计器禁用代码

c# - Windows Phone 7 - 使用 WebClient 处理 Application_UnhandledException 中的错误

javascript - 当我回到 wp8 中的应用程序时恢复相机?

Silverlight 4,子类化 WebClient

windows-phone-7 - 如何让消息框在 3 秒后消失?