如何将UI元素(如textBox)的焦点绑定(bind)到 View 模型?

我有带有枢轴控制的Windows Phone应用。基于 Activity 的枢轴项目,我想将焦点设置为某些文本框。另外,当用户将文本插入文本框并按Enter键时,我想将焦点设置在文本框以外的其他位置以关闭虚拟键盘。

如何使用Caliburn Micro View 模型执行此操作?

最佳答案

我认为您无法通过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>

希望能帮助到你!

关于wpf - Caliburn Micro,聚焦MV,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20380910/

10-13 07:56