我想更改ItemsPanelTemplate内的StackPanel的方向。要更改Orientation,我已经实现了一个属性。是否有任何方法可以更改StackPanel的方向。我尝试了以下代码。.但是没有成功。

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

最佳答案

使用{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

关于c# - 在Windows Phone中从父项绑定(bind)到ItemsPanelTemplate内部,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11307531/

10-10 14:27