问题
I am having trouble getting an attached property value to propagate down the tree from a parent to a child in the visual hierarchy. The setup is as follows:
I have a custom panel that instantiates a Viewport3D. The Panel then handles the child added and removed to create and add an inherited Visual3D class for each child item.
I am trying to declare an attached property called AttachedToggle property. I would like to have this property reside in an external owner class called AttachedToggle which implements the single attached dependency property IsChecked and allow either the parent Panel or any of the children Visual3D elements to be able to change the value and have the other elements' instance values reflect the change. Neither the Panel nor the Visual3D class inherit from a common base. Can this be done?
I can successfully change both the parent and child instance value of IsChecked from application code using Set/GetValue but am unable to get the change to propagate.
回答1:
This should work fine, according to the docs on Property Value Inheritance. Make sure that your call to register the property looks like:
public static readonly DependencyProperty IsChecked =
DependencyProperty.RegisterAttached(
"IsChecked",
typeof(Boolean),
typeof(AttachedToggle),
new FrameworkPropertyMetadata(false,
FrameworkPropertyMetadataOptions.Inherits)
);
-Note the Inherits
flag. See the docs for FrameworkPropertyMetadata (and FrameworkPropertyMetadataOptions - you can use OverridesInheritanceBehavior
if needed ) as well.
回答2:
Im not sure that attached properties propogate down the logical tree, but you could try something like this:
<Panel a:ToggleSwitch="Binding Path=(a:ToggleSwitch),
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Panel}}" />
来源:https://stackoverflow.com/questions/4249413/getting-attached-property-inheritance-to-propagate