开发者

How to force a TextChanged event on a WPF TextBox and mantain the focus?

I am creatin开发者_Python百科g a numeric TextBox in WPF, with two buttons to increase and decrease the value.

I have create two RoutedCommand to manage the behiavor and they are working well. There is only one problem that I would like to solve. I would like that the control notifies all object binded to its TextProperty when an increase or decrease command is executed.

At the moment it sends the notification only when I change the focus to another control

Any help is really appreciated, Thank you


There is a simple way:

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

(I tested it on TextBox). Good Luck


Use UpdateSourceTrigger="Explicit" in the Binding and in TextChanged event update the BindingSource. so you are writing something like this:

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

instead do like this

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

and in TextChanged event handler update the binding.

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

and thats done. Hope it helps!!


The default behavior for the binding of the Text property on a TextBox is to update on LostFocus. You can change this in your custom control by overriding the metadata on the TextProperty in your static ctor:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜