for something more robust
If you want a robust application, you need a robust design.
If you're working with WPF, You need to leave behind the traditional event-based approach and understand and embrace The WPF Mentality.
I want to know when a user uses the mouse or keyboard to change the
listbox selection
Instead of handling events, putting a bunch of code behind, and hoping that the complexities of the Visual Tree will allow that to work, simply use proper DataBinding:
<ListBox ItemsSource="{Binding SomeCollection}"
SelectedItem="{Binding SelectedItem}"/>
to a proper ViewModel:
public class MyViewModel
{
public ObservableCollection<MyClass> SomeCollection {get;set;}
public MyClass SelectedItem {get;set;} //Don't forget INotifyPropertyChanged
}
- See how I'm not handling any events or putting any code behind. The Visual tree can do whatever it wants and raise as many events, and my code will still work.
- Also see how this approach is much cleaner because it allows a true separation between UI and data.
- I could go on forever about the advantages of proper MVVM, but I'm too lazy right now. Let me know if you need further help.