Here’s a basic MVVM
compliant way of getting the behaviour you want:
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ComboBox Margin="30,5,30,5"
IsEditable="True"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"
Text="{Binding NewItem, UpdateSourceTrigger=LostFocus}"/>
<TextBox Margin="30,5,30,5" />
</StackPanel>
</Window>
MainWindow.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string _selectedItem;
private ObservableCollection<string> _items = new ObservableCollection<string>()
{
"One",
"Two",
"Three",
"Four",
"Five",
};
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
public IEnumerable Items
{
get { return _items; }
}
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
public string NewItem
{
set
{
if (SelectedItem != null)
{
return;
}
if (!string.IsNullOrEmpty(value))
{
_items.Add(value);
SelectedItem = value;
}
}
}
protected void OnPropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
I had to place another control in the window as I have set the UpdateSourceTrigger
property of the Text
binding to LostFocus
. If there are no other controls in the window then the Combobox
will never lose focus.
I changed the update mode because the default update mode is Propertychanged
which will add a new item for each keystroke.
E.G. if you entered the text “Window”, the following would be added to your collection:
W
Wi
Win
Wind
Windo
Window