Answered by:
LogicalTreeHelper.GetChildren() does not work with my custom class
Question
- LogicalTreeHelper.GetChildren() is supposed to give me the object or collection (i.e. children) of a FrameworkElement (I assume that this method looks for the property specified by attribute ContentProperty and fetches the object or collection there).
LogicalTreeHelper.GetChildren() works fine with an established class such as Button, but I always get an empty IEnumerable when I call it on an object of my own custom class. Here is a simple code example:
publicpartial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Button btn = new Button();
btn.Content = "hello";
// this works fine, the IEnumerable contains one element "hello"
IEnumerable children1 = LogicalTreeHelper.GetChildren(btn);
Film test = new Film();
test.Title = "goodbye";
// this returns an empty IEnumerable
IEnumerable children2 = LogicalTreeHelper.GetChildren(test);
}
[ContentProperty("Title")]
public class Film : FrameworkElement
{
public object Title {get; set;}
}
The problem occurs even if I declare Title as a dependency property.
Thanks for any insight you may have.
hello
Answers
-
All replies
-
- Your comment was exactly what the doctor ordered. It appears that the XAML content property has no relation to what is added to the tree other than by convention. That is, it is simply wise to specify via ContentPropertyAttribute whatever property the control adds to the tree so that that property can be easily accessed in XAML. All the action to do the adding to the tree occurs in either the control's "set" method (such as setting the Content in button) or the "Add" method (e.g. adding children to a StackPanel. An example of how the "set" function is modified to add the control to the tree is shown in the MSDN description for FrameworkElement::AddLogicalChild Method.
Thanks again for your help. This cleared up a lot of confusion for me.
BTW, I looked up your Silverlight framework. A very interesting product.
hello