I’m binding an Observable collection to a combobox using the MVVM pattern.I can successfully bind to the combobox but now I’m looking for a way to get the SelectedItem property in my view model(I cannot simply call it because that would be braking the pattern)The way I picture it is that there must be some way to create a binding in XAML which points to the selected item and which I can later use in my view model.What I can’t seem to figure out is the how…
Any suggestions on how I can achieve this?
XAML
<ComboBox SelectedIndex="0" DisplayMemberPath="Text" ItemsSource="{Binding Path=DocumentTypeCmb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
Grid.Column="1" Grid.Row="4" Margin="0,4,5,5" Height="23"
HorizontalAlignment="Left" Name="cmbDocumentType" VerticalAlignment="Bottom"
Width="230" />
Code
//Obesrvable collection property
private ObservableCollection<ListHelper> documentTypeCollection = new ObservableCollection<ListHelper>();
public ObservableCollection<ListHelper> DocumentTypeCmb
{
get
{
return documentTypeCollection;
}
set
{
documentTypeCollection = value;
OnPropertyChanged("DocumentTypeCmb");
}
}
//Extract from the method where i do the binding
documentTypeCollection.Add(new ListHelper { Text = "Item1", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item2", IsChecked = false });
documentTypeCollection.Add(new ListHelper { Text = "Item3", IsChecked = false });
DocumentTypeCmb = documentTypeCollection;
//Helper class
public class ListHelper
{
public string Text { get; set; }
public bool IsChecked { get; set; }
}
Try this:
And the XAML:
You simply need to have a public property in your ViewModel that gets/sets the right type, then use a binding to assign the selected item to it. Note that the SelectedItem is a dependency proeprty so you can bind like this, but for the list controls SelectedItems (note the plural) is not a dependency property so you cannot bind it back to your VM – for this there is a simple workaround to use a behaviour instead.
Also note that I haven’t implemented property change notifications in my example, so if you change the selected item from the VM it will not update in the UI, but this is trivial to put in.