I’m learning the ins and outs of creating custom controls in WPF. The concepts I understand thus far:
- The code defines the control’s behavior.
- The template defines the control’s look and feel, the visual aspect.
- You can bind elements of the template to properties of the underlying control object.
If the template has multiple collection controls, such as StackPanels, how do you bind them so that they are populated by underlying collections? My first inclination was to make use of the DataContext of each StackPanel, but I couldn’t make it work. I get the feeling I’m missing a key concept that would solve this for me.
What did you want to be in these StackPanels? Panels are used for arranging items. If you want to show a collection of items, you probably want to be using an ItemsControl (or one of the many types of ItemsControls). An ItemsControl is very powerful- you can specify how the items are displayed and how the panel that they’re displayed on is displayed as well. You can even specify that the panel is a StackPanel. For example,
Then you wanted to bind to a list of items, which is very easy with an ItemsControl! In your case with the custom control, you may want to expose dependency properties on the control itself in the code-behind and then bind to those from the XAML. For example, you can create dependency properties for the various lists you have like this:
Then you can bind the ItemsSource property of your ItemsControls:
(in this case I assume that the custom control has a x:Name=”root”)
I hope this helps!