views:

332

answers:

1

Hi all,

I'm building a custom ItemsControl in Silverlight that (amongst other things) allows items to be displayed horizontally or vertically at runtime. How can I bind the Orientation property of the ItemsPanel to the Orientation property of my parent control? I've tried using TemplateBinding (which works inside the ControlTemplate) but does not seem to work inside the ItemsPanelTemplate, am I doing something wrong?

<Style TargetType="CustomItemsControl">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="{TemplateBinding Orientation}" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>
+3  A: 

Use a RelativeSource:

<Style TargetType="CustomItemsControl">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="{Binding Orientation, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type CustomItemsControl}}}" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

Edit after comment: Silverlight doesn't support RelativeSource, but this post by Colin Eberhardt explains how it can be implemented manually.

HTH, Kent

Kent Boogaart
Hi Kent, thanks for your answer, unfortunately I'm using Silverlight which does not seem to support the use of RelativeSource. Apologies for the confusion, I have updated my original question to clarify that I'm using Silverlight.
Paul Bevis
Hmm, I see. In that case, you might want to check out this post: http://www.scottlogic.co.uk/blog/wpf/2009/02/relativesource-binding-in-silverlight/
Kent Boogaart
+1: I'm using WPF and had the same problem; your answer was really helpful.
Heinzi