you can use the following class:
public static class ListBoxSelectedItems{
private static readonly DependencyProperty SelectedItemsBehaviorProperty =DependencyProperty.RegisterAttached("SelectedItemsBehavior" ,typeof(SelectedItemsBehavior),typeof(ListBox),null);public static readonly DependencyProperty ItemsProperty =DependencyProperty.RegisterAttached(
"Items" ,typeof(IList),typeof(ListBoxSelectedItems),new PropertyMetadata(null, ItemsPropertyChanged));public static void SetItems(ListBox listBox, IList list){listBox.SetValue(ItemsProperty, list); }
public static IList GetItems(ListBox listBox){ return listBox.GetValue(ItemsProperty) as IList; }
private static void ItemsPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var target = d as ListBox ;if (target != null ){
GetOrCreateBehavior(target, e.NewValue as IList );}
}
private static SelectedItemsBehavior GetOrCreateBehavior(ListBox target, IList list){
var behavior = target.GetValue(SelectedItemsBehaviorProperty)as SelectedItemsBehavior;
if(behavior == null){
behavior = new SelectedItemsBehavior (target, list);target.SetValue(SelectedItemsBehaviorProperty, behavior);}
return behavior;}
}
public class SelectedItemsBehavior{
private readonly ListBox _listBox;private bool _isListChanging = false ;private bool _isSelectionChanging = false ;private IList _boundList;public SelectedItemsBehavior(ListBox listBox, IList boundList){
_boundList = boundList;_listBox = listBox;SetSelectedItems();// attach the selection changed event_listBox.SelectionChanged += OnSelectionChanged;// attach the collection changed eventvar collectionChanged = _boundList as INotifyCollectionChanged;if(collectionChanged != null ){
collectionChanged.CollectionChanged += BoundList_CollectionChanged;}
}
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e){
// only fire this event when the list is not changing to prevent circular loopif (!_isListChanging){
_isSelectionChanging = true;_boundList.Clear();foreach (var item in _listBox.SelectedItems){
_boundList.Add(item);}
_isSelectionChanging = false;}
}
private void BoundList_CollectionChanged(object sender,System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// only fire this event when the list is not changing to prevent circular loopif (!_isSelectionChanging){
_isListChanging = true;SetSelectedItems();_isListChanging = false;}
}
private void SetSelectedItems(){
if (listBox.SelectionMode == SelectionMode .Single){
if (_boundList != null && _boundList.Count > 0)_listBox.SelectedItem = _boundList[0];}
else{
_listBox.SelectedItems.Clear();foreach(object item in _boundList){
// References in _boundList might not be the same as in _listBox.Itemsint i = _listBox.Items.IndexOf(item);if (i >= 0)_listBox.SelectedItems.Add(_listBox.Items[i]);}
}
}
private void ODataContextChanged(object sender, DependencyPropertyChangedEventArgs e){
SetSelectedItems();}
}