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?
Asked
Active
Viewed 1.0k times
0
-
What did you try up to know? Do you have some code to show? – gomi42 Jan 15 '14 at 07:03
-
Have you look on this? http://stackoverflow.com/questions/18516536/how-to-use-an-eventtocommand-with-an-editable-combobox-to-bind-textboxbase-textc – Sankarann Jan 15 '14 at 07:14
-
@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?](http://stackoverflow.com/help/how-to-ask) page from the [Help Center](http://stackoverflow.com/help). The questions that gomi42 asked you relate to this 'quality control' and are required by question authors. Many thanks and welcome to StackOverflow. – Sheridan Jan 15 '14 at 09:31
1 Answers
8
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
}
}
}

Sheridan
- 68,826
- 24
- 143
- 183
-
when i do something that the selected item changed,there is some problem. ie, when the first time , it's not working correctly...then after no problem...Any idea? – Jinesh Jan 28 '14 at 08:19
-
@JineshG, if you have another question, then please ask it as a new question. You can add a link to this question in it. – Sheridan Jan 28 '14 at 08:58
-
1How can you suddenly decide that this answer no longer answers your question after it has been marked as the accepted answer for 9 months? – Sheridan Oct 21 '14 at 12:50
-
1Then please share it here by adding it as an answer and accepting it. – Sheridan Oct 26 '14 at 22:46