Drake
Drake

Reputation: 8392

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

I am creating 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

Upvotes: 10

Views: 20272

Answers (3)

viky
viky

Reputation: 17689

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!!

Upvotes: 13

Shaipod
Shaipod

Reputation: 331

There is a simple way:

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

(I tested it on TextBox). Good Luck

Upvotes: 33

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

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));
}

Upvotes: 2

Related Questions