Binding.RelativeSource Property

Definition

Gets or sets the binding source by specifying its location relative to the position of the binding target. This is most often used in bindings within XAML control templates.

RelativeSource RelativeSource();

void RelativeSource(RelativeSource value);
public RelativeSource RelativeSource { get; set; }
var relativeSource = binding.relativeSource;
binding.relativeSource = relativeSource;
Public Property RelativeSource As RelativeSource
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
-or-
<Binding RelativeSource="{RelativeSource Self}"/>

Property Value

The relative location of the binding source to use. The default is null.

Examples

This XAML example is taken from the generic.xaml file that defines the default visual states for all XAML controls. This particular segment is one of the visual states for the ToggleSwitch control. Here, one of the animations defined by the visual state references properties of the control that exist specifically so that templates can access them and get run-time values that modify the animation. For the template XAML to get properties from the control where the template is applied, the binding must use {RelativeSource TemplatedParent} as the RelativeSource value.

<VisualStateGroup x:Name="ToggleStates">
  <VisualStateGroup.Transitions>
    <VisualTransition x:Name="DraggingToOnTransition"
      From="Dragging"
      To="On"
      GeneratedDuration="0">
      <Storyboard>
        <RepositionThemeAnimation TargetName="SwitchKnob" 
          FromHorizontalOffset="
          {Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplateSettings.KnobCurrentToOnOffset}"
        />
        <RepositionThemeAnimation TargetName="SwitchCurtain"
          FromHorizontalOffset="
          {Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplateSettings.CurtainCurrentToOnOffset}"
        />
      </Storyboard>
    </VisualTransition>
...
  </VisualStateGroup.Transitions>
</VisualStateGroup>

Remarks

Source, RelativeSource, and ElementName are mutually exclusive in a binding. If you have set one of these attributes, then setting either of the other two in a binding (through XAML or through code) will cause an exception. Setting RelativeSource in XAML always requires the use of the {RelativeSource} markup extension. This is also true if you are creating the entire binding as a {Binding} markup extension, in which case the {RelativeSource} markup extension is nested within the RelativeSource component of the expression.

You can't set the property values of a Binding object after that binding has been attached to a target element and target property. If you attempt this you'll get a run-time exception.

Applies to

See also