【发布时间】:2010-03-30 14:13:21
【问题描述】:
我在 WPF 中创建了一个数字文本框,有两个按钮来增加和减少值。
我创建了两个 RoutedCommand 来管理行为,它们运行良好。我只想解决一个问题。我希望控件在执行增加或减少命令时通知绑定到其 TextProperty 的所有对象。
目前它发送通知仅当我将焦点更改为另一个控件时
非常感谢任何帮助, 谢谢
【问题讨论】:
标签: c# .net wpf custom-controls
我在 WPF 中创建了一个数字文本框,有两个按钮来增加和减少值。
我创建了两个 RoutedCommand 来管理行为,它们运行良好。我只想解决一个问题。我希望控件在执行增加或减少命令时通知绑定到其 TextProperty 的所有对象。
目前它发送通知仅当我将焦点更改为另一个控件时
非常感谢任何帮助, 谢谢
【问题讨论】:
标签: c# .net wpf custom-controls
有一个简单的方法:
Text="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged}"
(我在 TextBox 上测试过)。 祝你好运
【讨论】:
Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged}" 似乎是最好的选择。
在绑定中使用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();
然后就完成了。 希望对你有帮助!!
【讨论】:
Text="{Binding YourBindableProperty, UpdateSourceTrigger=PropertyChanged}"?
在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));
}
【讨论】: