简体   繁体   中英

Attached Property collection inside a Panel

When I try to add an attached property collection to a Panel like so;

<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>

It's assigning it to the Grid instead... how can I attach it to a Panel?

Mkay it turns out the attached property was sharing one list instance with every single ui element so I had to use a rather hackish way of giving each element it's own list instance.

Before

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

After

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

With the getter now creating a new list instance for each ui element:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM