如何在WPF TextBox上强制触发TextChanged事件并保持焦点?

9

我正在使用 WPF 创建一个数字文本框,并带有两个按钮,用于增加和减少值。

我创建了两个 RoutedCommand 来管理行为,并且它们工作正常。但是只有一个问题我想解决。当执行增加或减少命令时,我希望控件通知其绑定到 TextProperty 的所有对象。

目前它仅在我将焦点更改为另一个控件时发送通知。

非常感谢您的帮助, 谢谢

3个回答

32

有一种简单的方法:

Text="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}"

(我在TextBox上测试过了。祝好运。)


1
+1. Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged}" 似乎是最好的选择。 - DK.

13

在绑定中使用 UpdateSourceTrigger="Explicit",并在TextChanged事件中更新BindingSource

<NumericTextBox x:Name="control" Text={Binding Path=MyProperty}/>

改为这样

<NumericTextBox x:Name="control" Text={Binding Path=MyProperty, UpdateSourceTrigger=Explicit}/>

TextChanged事件处理程序中更新绑定。

control.GetBindingExpression(NumericTextBox.TextProperty).UpdateSource();

完成了,希望能有所帮助!


@viky 非常感谢!我忘记了可以使用表达式“control.GetBindingExpression(NumericTextBox.TextProperty).UpdateSource();”,这太完美了。 我只在用户按增加和减少按钮时调用它,并在手动更改文本时使用正常行为。 - Drake
10
为什么不直接使用 Text="{Binding YourBindableProperty, UpdateSourceTrigger=PropertyChanged}" - Jonathan Perry

2

TextBox 的 Text 属性的默认绑定行为是在 LostFocus 时更新。您可以通过在静态构造函数中覆盖 TextProperty 上的元数据来更改此行为:

static NumericTextBox()
{
    TextProperty.OverrideMetadata(
        typeof(NumericTextBox),
        new FrameworkPropertyMetadata("", // default value
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            null,  // property change callback
            null,  // coercion callback
            true,  // prohibits animation
            UpdateSourceTrigger.PropertyChanged));
}

@abe 谢谢Abe,非常有用,但viky的答案对我的情况更灵活。 - Drake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接