Search code examples
silverlightmvvmlistboxcommandselectionchanged

How can I realize SelectionChanged in MVVM ListBox Silverlight


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


Solution

  • 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.
            }
        }
    }