0
votes

I have a textbox which is bound to a property ItemID like so.

private string _itemID;
public string ItemID {
    get { return _itemID; }
    set { 
        _itemID = value;
    }
}

The XAML of the text box is as follows:

<TextBox Text="{Binding Path=ItemID, Mode=TwoWay}" Name="txtItemID" />

The problem is, the value of ItemID does not update immediately as I type,
causing the Add button to be disabled (command), until I lose focus of the text box by pressing the tab key.

2
Hi Edwin, I think you should implement INotifyPropertyChanged event handler. This may be the reason why it isn't updating. The INotifyPropertyChanged is set within your Property and Notifies the UI that it has been changed. also, within your xaml, add; UpdateSourceTrigger=PropertyChanged - greg
I agree with you @gregory.bmclub - Shakti Prakash Singh
Did my answer help you? If it did, please mark it as an answer. Thanks. - Shakti Prakash Singh
Ah yes it does! My apologies. Its marked. - Edwin

2 Answers

5
votes

Yes, by default, the property would be updated only on lost focus. This is to improve performance by avoiding the update of bound property on every keystroke. You should use UpdateSourceTrigger=PropertyChanged.

Try this:

<TextBox 
    Text="{Binding Path=ItemID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
    Name="txtItemID" />

You should also implement the INotifyPropertyChanged interface for your ViewModel. Else, if the property is changed in the ViewModel, the UI would not get to know about it. Hence it would not be updated. This might help in implementation.

2
votes

You need to fire the OnPropertyChanged event in the setter, otherwise the framework has no way of knowing that you edited the property.

Here are some examples:

Implementing NotifyPropertyChanged without magic strings

Notify PropertyChanged after object update