4

我有一个ComboBox绑定的ObservableCollection. 当用户在列表中输入文本时ComboBox,如果项目不在列表中,代码会自动将新项目添加到列表中,我该怎么办?

<ComboBox Name="cbTypePLC"
          Height="22" 
          ItemsSource="{StaticResource TypePLCList}"
          SelectedItem="{Binding TypePLC}" IsReadOnly="False" IsEditable="True">
</ComboBox>
4

1 回答 1

10

将组合框的 Text 属性绑定到视图模型项,然后添加到那里的绑定集合中,例如,

Text="{Binding UserEnteredItem, UpdateSourceTrigger=LostFocus}"

将 UpdateSourceTrigger 更改为 LostFocus,因为默认 (PropertyChanged) 会将每个字符更改传达给您的视图模型。

// 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;} 
于 2013-07-23T09:45:49.907 回答