Panel中的附加属性集合

时间:2013-03-26 22:36:53

标签: c# wpf

当我尝试将附加属性集合添加到Panel时,如此;

<Grid x:Name="MainContent" Grid.Row="1">
    <StackPanel x:Name="MainContentSp">

        <do:AttachCollection.Col>
            <do:AttachItem x="y"/>
            <do:AttachItem x="z"/>
        </do:AttachCollection.Col>

        <TextBlock x:Name="tb1" Text="xx"/>
        <TextBlock x:Name="tb2" Text="yy"/>

    </StackPanel>
</Grid>

它正在将它分配给网格......我怎样才能将它附加到Panel?

1 个答案:

答案 0 :(得分:0)

Mkay事实证明附加属性与每个单独的ui元素共享一个列表实例,因此我不得不使用一种相当hackish的方式为每个元素提供它自己的列表实例。

public static readonly
    DependencyProperty
    XProperty =
        DependencyProperty
            .RegisterAttached
            ("X",
                typeof(List<X>),
                typeof(X),
                new PropertyMetadata(new List<X>()));

public static readonly
    DependencyProperty
    XProperty =
        DependencyProperty
            .RegisterAttached
-->         ("XInternal",
                typeof(List<X>),
                typeof(X));
-->(removed)

getter现在为每个ui元素创建一个新的列表实例:

public static List<X> GetX(UIElement element)
{
    var list = ((List<X>)(element.GetValue(XProperty)));
    if (list == null)
    {
        list = new List<X>();
        SetX(element, list);
    }
    return list;
}