Caliburn Micro,专注于MV

时间:2013-12-04 16:37:44

标签: wpf mvvm windows-phone-8 caliburn.micro

如何将UI元素(如textBox)焦点绑定到视图模型?

我有带有枢轴控制的Windows Phone应用程序。基于活动的透视项目,我想将焦点设置为某个文本框。此外,当用户将文本插入文本框并按Enter键时,我想将焦点设置在除文本框之外的其他位置以关闭虚拟键盘。

如何使用Caliburn Micro查看模型?

1 个答案:

答案 0 :(得分:2)

我认为你不能通过C.M.做到这一点。我会写一个这样的行为:

public class BindableFocusBehavior : Behavior<Control>
{
    public static readonly DependencyProperty HasFocusProperty =
        DependencyProperty.Register("HasFocus", typeof(bool), typeof(BindableFocusBehavior), new PropertyMetadata(default(bool), HasFocusUpdated));

    private static void HasFocusUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((BindableFocusBehavior)d).SetFocus();
    }

    public bool HasFocus
    {
        get { return (bool)GetValue(HasFocusProperty); }
        set { SetValue(HasFocusProperty, value); }
    }

    private void SetFocus()
    {
        if (HasFocus)
        {
            AssociatedObject.Focus();
        }
    }
}

像这样使用:

<TextBox>
    <i:Interaction.Behaviors>
        <wpfApplication2:BindableFocusBehavior HasFocus="{Binding SetFocus}"/>
    </i:Interaction.Behaviors>
</TextBox>

希望它有所帮助!