Click here to Skip to main content
15,890,882 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All,

I'm struggling a bit. If I have classes as below:

C#
public static class ClassName
{
    ...attached DP called 'ChildObjects', of type ChildCollection....
}


C#
public class ChildCollection : ObservableCollection<child>
{
}
</child>


I can add an attached dependency property definition to ClassName, of type ChildCollection, allowing me to do the below:

HTML
<grid>
  <classname.childobjects>
    <childcollection>
      <child someproperty="{Binding Etc}" />
      <child someproperty="{Binding Etc}" />
    </childcollection>
  <classname.childobjects>
<grid></grid></classname.childobjects></classname.childobjects></grid>


This works great - Child objects are derived from FrameworkElement and therefore have a datacontext. The only problem is ChildCollection - it is not a framework element therefore it means that it's not in the logical tree, so bindings on the Child objects don't work - let alone using things like 'FindAncestor'.

Is there a standard way to deal with this? I've looked for 'FrameworkElementCollection' that would add the children to the logical tree but with no luck. Before I dive into creating one, I would like to know if I'm missing something obvious!

Thanks in advance,

Dave
Posted

You're very close have a look at the UIElementCollection[^]
 
Share this answer
 
OK With a bit more research I found out exactly how to do this - make the collection a FreezableCollection<t> and make sure that the class you are making a collection from is derived from Freezable - then you get the datacontext set just as you should :)

There's a great example by Nishant here:

An MVVM friendly approach to adding system menu entries in a WPF application[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900