Posted by: Zeeshan Amjad | September 28, 2013

Editable ComboBox in MVVM


Creating an editable combo box in WPF is not very difficult, just set the IsEditable property to true. What makes it interesting is when we are trying to add a new item in the combo box that is not a part of it before using data binding or MVVM pattern. In other words doing it without any code behind.

Let’s first step to create a MVVM application using editable combo box without adding any new item in it. It is quite straight forward task.

This is simple and standard view model with two properties. First one is an observable collection stored the list of cities and the other one is selected city.

Code Snippet
public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<string> cities = new ObservableCollection<string>();
    private string selectedItem;

    public ViewModel()
    {
        this.Cities.Add("Boston");
        this.Cities.Add("Los Angeles");
        this.cities.Add("Frederick");
        this.cities.Add("Houston");

        this.SelectedCity = "Boston";
    }

    public ObservableCollection<string> Cities
    {
        set
        {
            this.cities = value;
            this.RaisePropertyChanged("Cities");
        }
        get
        {
            return this.cities;
        }
    }

    public string SelectedCity
    {
        set
        {
            this.selectedItem = value;
            this.RaisePropertyChanged("SelectedCity");
        }
        get
        {
            return this.selectedItem;
        }
    }

    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

 

The reason to create a selected city property is two fold. First we want to show the selected item in the textbox (or any other control). But the most important one is when we are going to add the functionality of add items in the combo box, then it will be more useful, because we don’t only add the items in the combo box, but also set that value as a selected item. Obviously it doesn’t make sense that first user entered a new entry, then select it from the combo box, it should be one step.

Now lets see the fun part i.e. going to add a new city in the editable combo box. To do this we are going to use the Text property of the combo box. We already used the ItemsSource and SelectedItems property and this time we are going to introduce one more property in my view model class to bind with TextProperty of the combo box.

And here rubber meets the road. We will add the new entry in the city collection. In addition to this, we return the selected city as a getter of that property, because there is no field to backup this. It would be something like this.

Code Snippet
public string NewCity
{
    set
    {
        if (!string.IsNullOrEmpty(value))
        {
            this.Cities.Add(value);
            this.SelectedCity = value;
        }
    }
    get
    {
        return this.SelectedCity;
    }
}

 

Here is a complete XAML of our program.

Code Snippet
<Window x:Class="WpfEditableCombo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="Editable ComboxBox" Height="300" Width="400">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ComboBox Grid.Row="0" Margin="5" VerticalAlignment="Center" IsEditable="True"
                  ItemsSource="{Binding Cities}"
                  SelectedItem="{Binding SelectedCity}"
                  Text="{Binding NewCity, UpdateSourceTrigger=LostFocus}"/>
        <TextBox Grid.Row="1" Margin="5" VerticalAlignment="Center"
                   Text="{Binding SelectedCity}"/>
    </Grid>
</Window>

 

The only important thing to note here is the UpgradeSourceTrigger property. We set it to LostFocus, so it will call the setter of NewItems property only when we lost the focus from the combobox. In other words, we only add items in the collection when we are done with out editing. But you should have another control there to get the focus and that is exactly the reason I have TextBox, not TextBlock here.

Here is the initial screen shot of the program.

EditableCombo_01

And here is a screen shot after adding “New York” in the combo box.

EditableCombo_02

Advertisements

Responses

  1. Your TextBox seems ugly. We need too some mechanism to force insertion in place. This could be a “Return” keystroke capture to force insertion but only after combobox editing.

    • Thanks for visiting my blog and point this out. I will take a look at this and will see how can I make it better.
      Best regards
      Zeeshan Amjad

  2. This site teach me alot….Thanks to you all….

    • I am glad that you find this site useful. Thanks to visiting and liking it.
      Best regards
      Zeeshan Amjad


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: