本文介绍了WPF-组合框-当用户以组合形式输入文本时添加项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ComboBoxObservableCollection绑定.当用户在ComboBox中输入文本时如何处理,如果项目不在列表中,则代码会自动将新项目添加到列表中?

I have a ComboBox binded with an ObservableCollection. How can I do when user enter a text in the ComboBox, if item not in the list, the code automatically add a new item to the list?

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

推荐答案

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

Bind Text property of your combo box to your view model item and then add to the bound collection there, like,

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

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

Change the UpdateSourceTrigger to LostFocus because default (PropertyChanged) will communicate each character change to your 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;}

这篇关于WPF-组合框-当用户以组合形式输入文本时添加项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:40