Why does binding fail when binding a child element to another element when the parent succeeds?

与世无争的帅哥 提交于 2019-12-06 13:17:46
Jeremy White

The short answer to a long question is that Microsoft doesn't expect you to derive from FrameworkElement without doing a little plumbing.

Just doing derivation, breaks the logical tree which is used when doing binding by element name.

You probably also have to plum up the visual tree, and overload the arrange/measure parts of framework element. (We don't do that here as we aren't visual in the example.)

In this specific case we need to add any children of your object to the logical tree or break the ability to bind child elements.

A good example of someone who solved this is here

Information on overriding the logical tree is here

Anyways, the code needed to fix this SIMPLE example only relied on the logical tree (as the child object isn't really visual.)

Adding this function and changing the dependency property makes the binding work.

        private static readonly DependencyProperty ChildElementProperty =
                    DependencyProperty.Register("ChildElement",
                    typeof(MyChildElement),
                    typeof(MyFrameworkElement),
                    new PropertyMetadata(OnChildElementChanged));

    private static void OnChildElementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MyFrameworkElement control = d as MyFrameworkElement;

        if (e.OldValue != null)
        {
            control.RemoveLogicalChild(e.OldValue);
        }

        control.AddLogicalChild(e.NewValue);
    }

First, when you setup the xaml like this:

<my:MyFrameworkElement x:Name="ParentName" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ButtonReferenceInParent="{Binding ElementName=buttonisme}"/>
<my:MyChildElement x:Name="ChildName" ButtonReferenceInChild="{Binding ElementName=buttonisme}"/>

It works. I did this because I suspect a visual tree upwards traversal search for the Element Name you use in the binding.

I am still figuring out how the binding can be succesfull in your nested scenario. But maybe this may give you some hint...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!