文本框绑定属性值不会立即更新

时间:2013-05-21 08:14:07

标签: c# wpf mvvm

我有一个文本框,它绑定到属性ItemID,就像这样。

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

文本框的XAML如下:

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

问题是,ItemID的值在我输入时不会立即更新,
导致Add按钮被禁用(命令),直到我通过按Tab键失去文本框的焦点。

2 个答案:

答案 0 :(得分:5)

是的,默认情况下,仅在丢失焦点时才会更新属性。这是为了通过避免每次击键时更新绑定属性来提高性能。您应该使用 UpdateSourceTrigger = PropertyChanged

试试这个:

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

您还应该为ViewModel实现INotifyPropertyChanged接口。否则,如果在ViewModel中更改了属性,UI将无法了解它。因此它不会更新。 This可能有助于实施。

答案 1 :(得分:2)

您需要在setter中触发OnPropertyChanged事件,否则框架无法知道您编辑了该属性。

以下是一些例子:

Implementing NotifyPropertyChanged without magic strings

Notify PropertyChanged after object update

相关问题