Silverlight 3’s New {RelativeSource} Markup Extension

One of the more obscure features introduced in Silverlight 3 is the {RelativeSource} markup extension. It’s poorer than its counterpart in WPF because the Silverlight version supports only two modes: Self and TemplatedParent. There are precious few examples out there demonstrating why you’d ever need {RelativeSource} in Silverlight. Here’s one example.

Suppose you’re building a custom control named SuperSlider that wraps (and presumably adds functionality to) the built-in Slider control, and that the default control template looks something like this:

<Style TargetType=”local:SuperSlider”>

  <Setter Property=”Template”>

    <Setter.Value>

      <ControlTemplate TargetType=”local:SuperSlider”>

        <Slider Value=”{TemplateBinding Value}” />

      </ControlTemplate>

    </Setter.Value>

  </Setter>

<

p class=”MsoNormal”></Style>

It looks reasonable, but try setting SuperSlider’s Value property and you’ll find that the thumb doesn’t move. In addition, if the user slides the Slider control’s thumb, SuperSlider’s Value property doesn’t change. Why? Because a TemplateBinding is inherently a 1-way binding. You need a 2-way binding to forge a robust connection between SuperSlider’s Value property and the Slider’s Value property.

In Silverlight 2, you had to write code to overcome this. In Silverlight 3, you can do it declaratively by combining {Binding} with {RelativeSource}: 

<Style TargetType=”local:SuperSlider”>

  <Setter Property=”Template”>

    <Setter.Value>

      <ControlTemplate TargetType=”local:SuperSlider”>

        <Slider Value=”{Binding Value, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}” />

      </ControlTemplate>

    </Setter.Value>

  </Setter>

</Style>

That’s one use for {RelativeSource} in Silverlight: creating 2-way template bindings. There are others, and for examples you need look no further than the default control templates for ListBox and a handful of other controls included in Silverlight 3.

Stay Informed

Sign up for the latest blogs, events, and insights.

We deliver solutions that accelerate the value of Azure.
Ready to experience the full power of Microsoft Azure?

Atmosera is thrilled to announce that we have been named GitHub AI Partner of the Year.

X