I am new to wpf and MVVM, and I've spent all day trying to get the value of a ComboBox to my ViewModel on SelectionChanged. I want to call a function in the selection changed process. In mvvm, what is the solution for it?
0
votes
What did you try up to know? Do you have some code to show?
– gomi42
Have you look on this? stackoverflow.com/questions/18516536/…
– Sankarann
@JineshG, on this website, users are asked to follow a basic set of rules regarding the asking and answering of questions in order to maintain a high standard of content. Your question falls short of that high standard. As such, can you please take a moment to read through the How do I ask a good question? page from the Help Center. The questions that gomi42 asked you relate to this 'quality control' and are required by question authors. Many thanks and welcome to StackOverflow.
– Sheridan
1 Answers
8
votes
In MVVM, we generally don't handle events, as it is not so good using UI code in view models. Instead of using events such as SelectionChanged
, we often use a property to bind to the ComboBox.SelectedItem
:
View model:
public ObservableCollection<SomeType> Items { get; set; } // Implement
public SomeType Item { get; set; } // INotifyPropertyChanged here
View:
<ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding Item}" />
Now whenever the selected item in the ComboBox
is changed, so is the Item
property. Of course, you have to ensure that you have set the DataContext
of the view to an instance of the view model to make this work. If you want to do something when the selected item is changed, you can do that in the property setter:
public SomeType Item
{
get { return item; }
set
{
if (item != value)
{
item = value;
NotifyPropertyChanged("Item");
// New item has been selected. Do something here
}
}
}