![](/img/trans.png)
[英]System.Controls.ComboBox - How do I get it to add an item that does not exist in its Itemssource?
[英]Add combobox text to its Itemssource
我有一個通過MVVM綁定到名為Tenderness
的表的組合框。 我正在使用Entity Framework,它可以正確顯示所有記錄,但是我需要為其添加其他功能。 假設用戶鍵入了組合框的Itemssource中未包含的文本,我希望能夠直接將其添加到表中,然后也更新Itemssource。 現在,我想不用MVVM就能做到這一點,我想知道如何使用MVVM來實現。
只需執行您之前在LostFocus
事件處理程序中將源屬性的設置器綁定到ComboBox
的Text
屬性的操作即可。
查看模型:
public ObservableCollection<string> Items { get; } = new ObservableCollection<string>() { "a", "b", "c" };
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged(nameof(Text));
//add the missing value...
if (!Items.Contains(_text))
Items.Add(_text);
}
}
private string _selectedItem;
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
視圖:
<ComboBox IsEditable="True" Text="{Binding Text, UpdateSourceTrigger=LostFocus}" ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.