3

Is it possible to notify the “parent” if an attached property changes?

I am troubled with a WPF problem. I have a class, “ContainerVisual”, (actually a visual3D, but that should be irrelevant) that defines an attached property “IsChildVisible”. In XAML I then use this visual and add a number of children to it. Each child uses the attached property, and binds its value to a property in the view-model. When the property in the view-model changes from true to false, the child should disappear, and if it changes back to true, the child should reappear.

To make this possible, I have logic in the ContainerVisual that handles this. I then listen to the changed event on the dependency property like this:

public static readonly DependencyProperty IsChildVisibleProperty = 
    DependencyProperty.RegisterAttached("IsChildVisible", typeof(bool),
    typeof(ContainerVisual), new UIPropertyMetadata(true, IsChildVisiblePropertyChanged));

private static void IsChildVisiblePropertyChanged(DependencyObject d, 
    DependencyPropertyChangedEventArgs e) {}

So far so good. My problem is just that the sender, the DependencyObject that comes with the event, is the child, not the parent. Usually this is not a big problem since you can use a tree helper class to get the parent, but that requires that the visual is in the visual/logical tree in the first place. If the value was changed from false to true, I need to notify the “parent” to put the object back inside the tree. Of course the object doesn’t have a parent at this point, so to find it will be hard...

So my question is this: Is it possible to get a notification in the instance of the class that defines the attached property (in my case the instance of the ContainerVisual class), if an object uses the attached property (the child) changes the property’s value?

If this is impossible, is there a way for me to hide a visual child without removing it from the visual and/or logical tree?

EDIT: If it helps, I have stored the reference to all potential children. I only need to call a parameter- less public method in my ContainerVisual instance...

H.B.
  • 166,899
  • 29
  • 327
  • 400
Sverre
  • 147
  • 8
  • Why does the parent handle the visibility in the first place? Why don't you simply bind the `Visibility` property of the children to the VM property? – Kent Boogaart Oct 05 '11 at 08:04
  • The Visual3D (or actually ModelVisual3D) doesn’t have a Visibility property. That’s what I am trying to create. As far as I can see, the children are visible if, and only if, they are in the visual tree. My solution is therefore to add or remove them from the tree depending on conditions I specify in the view-model. – Sverre Oct 05 '11 at 13:22

0 Answers0