在Windows Phone中从Parent中绑定ItemsPanelTemplate

时间:2012-07-03 08:54:47

标签: c# xaml windows-phone-7.1 itemspaneltemplate

我想更改ItemsPanelTemplate内部的StackPanel的Orientation ...要更改Orientation我实现了一个属性..有没有办法改变StackPanel的方向。我尝试了以下代码..但它没有成功。

<Setter Property="ItemsPanel">
    <Setter.Value>
        <ItemsPanelTemplate>
             <StackPanel Orientation="{Binding MyOrientation,RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Left" />
        </ItemsPanelTemplate>
    </Setter.Value>
</Setter>       

2 个答案:

答案 0 :(得分:3)

使用{RelativeSource AncestorType = YourItemsControlType}

<强> MyItemsControl.cs:

namespace MyNamespace.Controls
{
    public partial class MyItemsControl : ItemsControl
    {
        public static readonly DependencyProperty MyOrientationProperty =
            DependencyProperty.Register(
            "MyOrientation",
            typeof(Orientation),
            typeof(MyItemsControl));

        public Orientation MyOrientation
        {
            get { return (Orientation)GetValue(MyOrientationProperty); }
            set { SetValue(MyOrientationProperty, value); }
        }
    }
}

<强> MyItemsControls.xaml

<Style xmlns:source="clr-namespace:MyNamespace.Controls" TargetType="source:MyItemsControl">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel 
                    Orientation="{Binding Orientation, 
                        RelativeSource={
                            RelativeSource AncestorType=source:MyItemsControl
                        }
                    }"
                    HorizontalAlignment="Left" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

参考: http://msdn.microsoft.com/en-us/library/ms743599%28v=vs.110%29.aspx

答案 1 :(得分:1)

RelativeSource.TemplatedParent适用于ControlTemplates

参考一些样本here