【问题标题】:How to force a TextChanged event on a WPF TextBox and mantain the focus?如何在 WPF TextBox 上强制 TextChanged 事件并保持焦点?
【发布时间】:2010-03-30 14:13:21
【问题描述】:

我在 WPF 中创建了一个数字文本框,有两个按钮来增加和减少值。

我创建了两个 RoutedCommand 来管理行为,它们运行良好。我只想解决一个问题。我希望控件在执行增加或减少命令时通知绑定到其 TextProperty 的所有对象。

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

非常感谢任何帮助, 谢谢

【问题讨论】:

    标签: c# .net wpf custom-controls


    【解决方案1】:

    有一个简单的方法:

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

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

    【讨论】:

    • +1。 Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged}" 似乎是最好的选择。
    【解决方案2】:

    在绑定中使用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();”那是完美的。我只在用户按下增加和减少按钮并在手动更改文本时使用正常行为时才调用它。
    • 为什么不直接使用Text="{Binding YourBindableProperty, UpdateSourceTrigger=PropertyChanged}"
    【解决方案3】:

    TextBox 上绑定 Text 属性的默认行为是在 LostFocus 上更新。您可以通过覆盖静态 ctor 中 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回答对我来说更灵活
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多