How can I realize SelectionChanged in MVVM ListBox Silverlight

Thomas Wingfield picture Thomas Wingfield · Jan 1, 2012 · Viewed 13.6k times · Source

The ListBox control does not implement a Command property. I have to attach some functionality to the SelectionChanged event. Somebody knows how can I do it? Please help me

Answer

Cameron MacFarland picture Cameron MacFarland · Jan 1, 2012

I prefer using a binding to the SelectedItem and implementing any functionality in the setting of the binding property.

<ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />

...

public class ViewModel
{
    public IEnumerable<Item> Items { get; set; } 

    private Item selectedItem;
    public Item SelectedItem
    {
        get { return selectedItem; }
        set
        {
            if (selectedItem == value)
                return;
            selectedItem = value;
            // Do logic on selection change.
        }
    }
}