RelativeSource.AncestorType Property

Gets or sets the type of ancestor to look for.

Namespace:  System.Windows.Data
Assembly:  System.Windows (in System.Windows.dll)


Public Property AncestorType As Type
public Type AncestorType { get; set; }

Property Value

Type: System.Type
The type of ancestor. The default value is nulla null reference (Nothing in Visual Basic).


If the Mode property is not set explicitly, setting the AncestorType or the AncestorLevel property will implicitly lock the Mode property value to FindAncestor.


The following Silverlight 5 code example demonstrates the use of the AncestorType property. In this example, a ListBox is bound to a collection of Customer objects. Each item in the list box is bound to a single Customer in the collection, and its visual appearance is defined by the ItemTemplate property. Because of the item-to-customer binding, the template can bind the TextBlock.Text property directly to the Customer.Name property without qualification. However, the FontSize property is bound to a property of the page-level data context, which is inaccessible from the Customer object.

For this reason, the FontSize binding uses the RelativeSource markup extension with AncestorType set to UserControl, and a binding path of DataContext.CustomFontSize. This means that the binding uses the nearest UserControl ancestor as the data source, then binds to the CustomFontSize property of the object assigned to the DataContext property. If there were multiple, nested UserControl instances and the template needed to bind to an even higher-level data source, it could specify an AncestorLevel value of 2 or more.

<UserControl x:Class="SL5DataBindingFeatures.RelativeSourceFindAncestorTestPage"
  d:DesignHeight="300" d:DesignWidth="400">

    <local:CustomerViewModel CustomFontSize="35">
          <local:Customer Name="Customer1"/>
          <local:Customer Name="Customer2"/>

  <Grid x:Name="LayoutRoot" Background="White">

    <ListBox ItemsSource="{Binding Customers}">
          <TextBlock Text="{Binding Name}" 
            FontSize="{Binding DataContext.CustomFontSize, 
            RelativeSource={RelativeSource AncestorType=UserControl}}"/>

Public Class Customer
    Public Property Name As String
End Class

Public Class CustomerCollection
    Inherits ObservableCollection(Of Customer)
End Class

Public Class CustomerViewModel
    Public Property CustomFontSize As Double
    Public Property Customers As CustomerCollection
End Class
public class Customer { public string Name { get; set; } }
public class CustomerCollection : List<Customer> { }
public class CustomerViewModel
    public double CustomFontSize { get; set; }
    public CustomerCollection Customers { get; set; }

Version Information


Supported in: 5


For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.