What I want to do:
I have a ListBox bound to an ObservableCollection<MyClass>. When I select an item, I want to display some of its properties in some labels. What are the steps here? I have set the content of labels to {Binding Path=PropertyName}. What should be their DataContext?
How I was going do it: I’m keeping a private variable in my window’s code-behind called MyClass selectedItem, and I would like all bindings to point to that variable and its properties. It just seems more “semantic” to me, to bind to a variable with a clear meaning within the code logic, than to a presentation element’s selected item.
This variable can, and will, reference a different MyClass instance at any given time (I’ll change it in ListBox SelectionChanged handler). I want the bindings to reflect that – to always point to the properties of the instance currently referenced by selectedItem. Will this just work? Will the binding always point to the object that the variable points to? Or will it point to the object the variable is referencing at the moment I set up the binding? (the latter would be my guess)
Possible alternatives I can think of: Bind to listbox’s SelectedItem instead of the variable referencing it. If this is the way to go, how to make it type-safe? How to ensure the binding will know it’s not working with a generic ListBoxItem, but a MyClass instance, so it can see its properties? Is this needed?
Any suggestions, or explanations why I’m being stupid, or alternative approaches from the more experienced? Thanks!
I would recommend using your alternate approach, I think this is the common way to do what you want. If you dont fill your ListBox in code-behind or in your XAML, the SelectedItem-property will hold the MyClass instance and not a ListBoxItem instance.
Then you either take the SelectedItem property of your ListBox as DataContext of your labels or you create a property of Type MyClass in your ViewModel which you bind to the SelectedItem property (Mode=TwoWay). Then you can bind to its properties like so:
In this case the DataContext of your Labels has to be the ViewModel.