我有一个ComboBox
绑定了ObservableCollection
。如果用户在ComboBox
中输入文本,如果项目不在列表中,代码会自动将新项目添加到列表中,该怎么办?
<ComboBox Name="cbTypePLC"
Height="22"
ItemsSource="{StaticResource TypePLCList}"
SelectedItem="{Binding TypePLC}" IsReadOnly="False" IsEditable="True">
</ComboBox>
答案 0 :(得分:8)
将组合框的“绑定文本”属性绑定到视图模型项,然后添加到绑定集合中,例如,
Text="{Binding UserEnteredItem, UpdateSourceTrigger=LostFocus}"
将UpdateSourceTrigger更改为LostFocus,因为default(PropertyChanged)会将每个字符更改传达给您的viewmodel。
// user entered value
private string mUserEnteredItem;
public string UserEnteredItem {
get {
return mUserEnteredItem;
}
set {
if (mUserEnteredItem != value) {
mUserEnteredItem = value;
TypePLCList.Add (mUserEnteredItem);
// maybe you want to set the selected item to user entered value
TypePLC = mUserEnteredItem;
}
}
}
// your selected item
private string mTypePLC;
public string TypePLC {
get {
return mTypePLC;
}
set {
if (mTypePLC != value) {
mTypePLC = value;
// notify change of TypePLC INPC
}
}
}
// your itemsource
public ObservableCollection <string> TypePLCList { set; private set;}