tags:

views:

159

answers:

1

I am attempting to use XAML to represent and load a graph of custom types that form a semantic model for a business domain.

One thing I would like to do is to be able to obtain a reference to the "root object" of the graph from an object deeper in the tree. I cannot find any straightforward way of doing this other than resorting to barbarous practices like having the root object as a singleton.

Any ideas?

A: 

I don't know that this is a problem unique to XAML. All XAML is doing is instantiating your "child" objects and adding them to a collection property on the "parent" object. So if you had something like:

<my:Category Name="Products">
    <my:Category.Subcategories>
        <my:Category Name="Clothing" />
        <my:Category Name="Jewellery" />
    </my:Category.Subcategories>
</my:Category>

... then you'd end up with a "Products" category with two subcategories. It'd be up to you to code up your "Category" class in such a way that adding a subcategory saves a reference to the "owner" of that subcategory somewhere. I'd probably use a custom collection type (override the Add and Remove methods so that they set the "Parent" or "Owner" property on the object being added).

Matt Hamilton
Thanks. The problem I have is that the way XAML works for collection type properties I can see no way to get the XamlReader to pass in the "owning" object.
Raoul
But if the "Subcategories" property is of a type that you've defined (and implements ICollection) then you can do whatever you like when the "Add" method is called. That's what the XAML does, right? Call the Add method with each item? I don't know for sure.
Matt Hamilton
Absolutely one can create whatever Add() method one wants; the trick however is to get the XamlReader to invoke it and it only looks for the Add() methods defined on a limited set of interfaces, none of these support an Add() that facilitates passing in the parent object.
Raoul
No, don't define an Add that passes in the parent. Pass in the parent to the constructor. Then assign it in the standard Add(T item) method from ICollection.
Matt Hamilton
(The constructor of the collection itself, I mean. Presumably you create it in code when the window is created.)
Matt Hamilton
Aha! Thanks! I was being dense about this...
Raoul