I am new to C# and MVVM, and I\'ve spent all day trying to get the value of a ComboBox
to my ViewModel on SelectionChanged
. I have managed to figure it
Why not do it the simpler way
<ComboBox MaxHeight="25"
ItemsSource="{Binding Source}"
SelectedItem="{Binding TheSelectedItem, Mode=TwoWay}" />
In your ViewModel declare the combo box items and use a property "Source" to return it to the view
List<string> _source = new List<string>{"Item 1", "Item 2", "Item 3"};
public List<string> Source
{
get { return _source; }
}
Then define one property which holds the selected item
string _theSelectedItem = null;
public string TheSelectedItem
{
get { return _theSelectedItem; }
set { _theSelectedItem = value; } // NotifyPropertyChanged
}
Also don't forget to implement the INotifyPropertyChanged interface while setting the _source
If you just want to get notified when your current item changes, why not use tools that are already part of WPF instead of all these dependencies.
First get the underlying view to your collection and use the CurrentChanged event on it.
ComboBoxList = new ObservableCollection<string>();
var view = CollectionViewSource.GetDefaultView(ComboBoxList);
view.MoveCurrentTo(ComboBoxList[0]);
view.CurrentChanged += new EventHandler(ComboBoxCurrentChanged);
In your xaml you just bind your collection and set IsSynchronizedWithCurrentItem
to true.
<ComboBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ComboBoxList}"/>