C# 将组合框文本添加到其Itemssource

C# 将组合框文本添加到其Itemssource,c#,wpf,entity-framework,mvvm,combobox,C#,Wpf,Entity Framework,Mvvm,Combobox,我通过MVVM将一个组合框绑定到一个名为Tenderness的表中。我正在使用实体框架。它正确地显示所有记录,但我需要向它添加另一个功能。假设用户输入的文本不包含在组合框的Itemssource中,我希望能够将其直接添加到表中,然后更新Itemssource。现在我已经能够在没有MVVM的情况下做到这一点,我想知道,如何使用MVVM实现它 只需在绑定到组合框的Text属性的源属性的setter中执行之前在LostFocus事件处理程序中执行的操作即可 查看模型: public Observabl

我通过MVVM将一个组合框绑定到一个名为
Tenderness
的表中。我正在使用实体框架。它正确地显示所有记录,但我需要向它添加另一个功能。假设用户输入的文本不包含在组合框的Itemssource中,我希望能够将其直接添加到表中,然后更新Itemssource。现在我已经能够在没有MVVM的情况下做到这一点,我想知道,如何使用MVVM实现它

只需在绑定到
组合框的
Text
属性的源属性的setter中执行之前在
LostFocus
事件处理程序中执行的操作即可

查看模型:

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}" />
publicobservablecollection Items{get;}=newobbservablecollection(){“a”、“b”、“c”};
私有字符串_文本;
公共字符串文本
{
获取{return\u text;}
设置
{
_文本=值;
OnPropertyChanged(名称(文本));
//添加缺少的值。。。
如果(!Items.Contains(_text))
项目。添加(_文本);
}
}
私有字符串_selectedItem;
公共字符串SelectedItem
{
获取{return\u selectedItem;}
设置
{
_选择editem=值;
OnPropertyChanged(名称(SelectedItem));
}
}
查看:

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}" />


您可以展示一下您“在没有MVVM的情况下是如何做到这一点的”吗?向组合框的文本框部分添加一个委托
失去焦点
事件处理程序,检查当前文本,如果它包含在组合框项中,则跳过,否则将其添加到数据库中,然后刷新组合框的项目。是的,这会将新添加的文本添加到ObservableCollection,现在如何将其添加到数据库?这是一个完全不同的问题。但是,您可以像以前在LostFocus事件处理程序中一样执行此操作。您曾问过如何“使用MVVM实现这一点”,我们已经回答了您的问题。谢谢!但是,我是否可以在ObservableCollection发生更改时引发一个事件,并使其向实体添加新项?ObservableCollection类已经引发CollectionChanged事件。最后一个问题,为了将其添加到数据库中,我将如何告诉可观察集合哪个是已添加的新项?