I have this ListBox which is bound to an ObservableCollection. Each object in the list implements an interface called ISelectable
public interface ISelectable : INotifyPropertyChanged
{
event EventHandler IsSelected;
bool Selected { get; set; }
string DisplayText { get; }
}
I want to keep track of which object is selected regardless of how it is selected. The user could click on the representation of the object in the ListBox but it could also be that an object is selected via code. If the user selects an object via the ListBox I cast the the selected item to an ISelectable and set the Selected property to true.
ISelectable selectable = (ISelectable)e.AddedItems[0];
selectable.Selected = true;
My problem is that when I select the object using code I can't get ListBox to change the selected item. I'm using a DataTemplate to show the selected object in a different color which means everything is displayed correctly. But the ListBox has the last object the user clicked as the SelectedItem which means that item can't be clicked without first selecting another object in the list.
Anyone got any idea on how to solve this? I pretty sure I can accomplish what I want by writing some custom code to handle the Mouse and Keyboard events but I rather not. I have tried adding a SelectedItem property to the collection and bind it to the ListBox's SelectItemProperty but no luck.