简体   繁体   中英

Textbox - bound property value does not update immediately

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM