Binding to a parent list control properties within a DataTemplate in WPF

I had this problem in WPF: I created a custom control, i.e. MyItemsControl derived from ItemsControl. And then I instantiated it and data bound the ItemsSource to a simple collection of objects.
MyItemsControl defined a DataTemplate to use as its ItemTemplate.
Within the DataTemplate, I wanted to use some of the parent MyItemsControl properties (defined in my custom class). For example, I wanted to have a new property in MyItemsControl class named CornerRadius, that I intended to use as the roundness for the rectangles that I used to draw the data template for the item.
However it was very difficult for me to find the required syntax for this binding. If I used TemplateBinding instead of binding, or RelativeSource with TemplatedParent I always got an exception saying that the CornerRadius is not a property of the ContentPresent object (which was the templated parent). Instead I needed to find the ancestor of my control type, using this complex call (maybe it helps somebody):

RadiusX="{Binding Path=CornerRadius, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyItemsControl}}}"


About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in Computers and Internet. Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s