Santiago Blanco on .Net

Finding solutions to my everyday programming problems

WPF – Bind to a parent DataContext from within a DataTemplate

Posted by Santiago Blanco on January 29, 2010

To bind to a property on the Presenter or ViewModel attached to the DataContext on the parent view or control from inside a DataTemplate you have to use the RelativeSource property with the value “FindAncestor” and the type of the control with the DataContext you are looking for.

The most common mistake I’ve seen using this, is people forgetting to use the {x:Type yourControlType} markup extension for the AcestorType property and using “AncestorType=yourControlType” instead.

Here is an example:

  1. Width=“{Binding DataContext.EquipmentItemSize, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}
  2.        

 

where “EquipmentItemSize” is a property on the Presenter or ViewModel that follows the INotifyPropertyChanged pattern.

Advertisements

One Response to “WPF – Bind to a parent DataContext from within a DataTemplate”

  1. xr said

    good example, solved real issue

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: