My first question here on the Stack. Forgive me for the bad explanation in advance.
I am working on my first MVVM application (Silverlight). I have a custom user control that contains a ListBox to show navigation items. This control is placed in my main xaml page. I don’t know if I need to create a composite view model (my main page view model) with a view model especially for the custom control in it or if there is some way to elevate the ListBox properties that I need to bind to.
Through XAML I don’t know how to bind, let’s say, the ItemsSource property of the ListBox inside the custom control to my main page viewmodel. Basically, I’m at the point that I am questioning my design decision for trying to bind the custom control through my main page view model.
What I have done so far is create dependency properties for the custom control and try to tunnel those dependency properties down to the ListBox properties. I’ve achieved success with this method for ItemsSource but am having issues with SelectedItem.
Even if I do get SelectedItem to work, it still feels Wrong. Thanks for any advice in advance.
The
UserControlshould inherit theDataContextfrom its parent control, unless you are setting it directly. You can then bind to the properties on your view model from yourUserControl.If you would like to create a
ViewModelspecifically for theUserControl, you can also do that. You would then expose it as a property on your mainViewModel, and bind to it in the MainPage. Example:And then in the view:
Your
ChildViewModelwould then contain properties likeSelectedItemto bind yourListBoxto.