Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding to parent ItemsControl from inside of child ItemsControl data template

Tags:

c#

.net

binding

wpf

I need to be able to bind to a parent ItemsControl's properties from inside of a child ItemsControl data template:

<ItemsControl ItemsSource="{Binding Path=MyParentCollection, UpdateSourceTrigger=PropertyChanged}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>

                <ItemsControl ItemsSource="{Binding Path=MySubCollection}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=MyParentCollection.Value, UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Let's assume that MyParentCollection (the outer collection) is of the following type:

public class MyObject
{
    public String Value { get; set; }
    public List<MyChildObject> MySubCollection { get; set;
}

And let's assume that MyChildObject from the above class is of the following type:

public class MyChildObject
{
    public String Name { get; set; }
}

How can I bind to MyParentCollection.Value from inside of the inner data template? I can't really use a FindAncestor by type because they both all levels use the same types. I thought maybe I could put a name on the outer collection and use an ElementName tag in the inner binding, but that still couldn't resolve the property.

Any thoughts?

like image 874
Robert Petz Avatar asked Jun 19 '13 08:06

Robert Petz


1 Answers

saving the parent item in the tag of the child itemscontrol could work

    <DataTemplate>

            <ItemsControl ItemsSource="{Binding Path=MySubCollection}" Tag="{Binding .}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Tag.Value, RelativeSource={RelativeSource  AncestorType={x:Type ItemsControl}}}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

    </DataTemplate>

its not tested but give you a hint in the right direction :)

like image 198
blindmeis Avatar answered Oct 06 '22 17:10

blindmeis