繁体   English   中英

ApplicationBar命令之前的LostFocus

[英]LostFocus before ApplicationBar Command

我将TextBox绑定到ViewModel的属性。 当用户单击ApplicationBar按钮时,正在调用命令(我使用的是BindableApplicationBar,可以在NuGet上找到它)。 问题在于,当用户键入TextBox并立即单击“应用程序按钮”时,不会调用TextBox的设置器,这意味着ButtonCommand使用的是旧文本。

我已经看到了很多解决方案,但是我无法在自己的情况下使用它们。 唯一的“解决方案”是摆脱ApplicationBar并使用一个位于Keyboard后面的按钮(当用户单击TextBox时弹出该按钮。我使用的是Windows Phone,所以这就是为什么有KeyBoard的原因。) ..)。 因此,用户必须单击其他位置才能使用按钮-> lostfocus。

一些解决方案:

保存之前WPF数据绑定

与UpdateSourceTrigger == LostFocus绑定不会触发菜单或工具栏交互

我不能使用UpdateSourceTrigger = PropertyChanged,而且我正在使用MVVM,所以我也不想使用CodeBehind。 如果没有CodeBehind没有其他方法可以做到这一点,那就可以了。

这里发生的问题(或框架中的错误?)是AppBar不是真正的Silverlight控件,因此在窃取焦点方面的处理方式有所不同。 我不确定这是否适合您的设计,但是在我的一个应用程序中,我使用了以下模式:

    void appBarButton_Click(object sender, EventArgs e)
    {
        // removal of focus from the TextBox to the Page will force the bind.
        this.Focus();

        // wait till the next UI thread tick so that the binding gets updated
        Dispatcher.BeginInvoke(() =>
        {
            // at this point the binding is updated
            MessageBox.Show(RandomText);
        });
    }

这有点麻烦,但是我使用了一个辅助函数来包装许多不同的路径,以使他们不必知道额外的调度,也不必知道哪个控件在按下按钮后会抢走焦点。

我过去使用的一种解决方案是,只要文本框的内容发生更改,而不是失去焦点时,就更新绑定。

一个简单,可重用的方法就是行为。

像这样:

public class RebindOnTextChanged : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.TextChanged += this.TextChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        this.AssociatedObject.TextChanged -= this.TextChanged;
    }

    private void TextChanged(object sender, TextChangedEventArgs e)
    {
        var bindingExpression = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
        if (bindingExpression != null)
        {
            bindingExpression.UpdateSource();
        }
    } 
}      

并像这样使用:

<TextBox Text="{Binding SomeProperty}">
    <i:Interaction.Behaviors>
        <behaviours:RebindOnTextChanged />
    </i:Interaction.Behaviors>
</TextBox>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM