How to set an item as selected in a combobox

msfanboy picture msfanboy · May 18, 2010 · Viewed 24.8k times · Source

It seems nobody has yet found a way to set the comboboxitem as selected with a SelectedItem="Binding Property".

Is the solution to use a IsSelected Property in the ViewModel object within the combobox itemssource?

Answer

Agies picture Agies · May 19, 2010

Our successful approach for binding a combobox is the following...

<ComboBox 
    ItemsSource="{Binding Path=AllItems}" 
    SelectedItem="{Binding Path=CurrentItem, Mode=TwoWay}" />
<TextBlock Text="{Binding Path=CurrentItem, Mode=TwoWay}" />

class public ItemListViewModel
{
    public ObservableCollection<Item> AllItems {get; set;}

    private Item _currentItem;
    public Item CurrentItem
    {
        get { return _currentItem; }
        set
        {
            if (_currentItem == value) return;
            _currentItem = value;
            RaisePropertyChanged("CurrentItem");
        }
    }
}