Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection Changed Event using MVVM

I have a listbox that contains a list of persons. When the user clicks on an item the viewModel should set the currentPerson object to the Object the user has clicked on.

I have to use a ViewModel for this, so no code inside the MainWindow.xaml.xs. Any Ideas how to solve this?

like image 825
Goot Avatar asked Oct 04 '12 13:10

Goot


1 Answers

That's very simple:

Add a property CurrentPerson to your ViewModel and bind it to the SelectedItem property of the ListBox.

Something like this:

View Model:

public Person CurrentPerson
{
    get { return _currentPerson; }
    set
    {
        if(value == _currentPerson) return;
        _currentPerson = value;

        NotifyOfPropertyChange("CurrentPerson");
    }
}

View:

<ListBox SelectedItem="{Binding CurrentPerson}" ...>
like image 130
Daniel Hilgarth Avatar answered Nov 04 '22 09:11

Daniel Hilgarth