If you’re using WPF, you probably encountered this obscure message of "Cannot find governing FrameworkElement or FrameworkContentElement for target element.", and found that your binding doesn’t work.

This message means that the binding engine could not locate the object of which to bind to.
This usually happens when the data context hierarchy chain is broken by a non-FrameworkElement object. Interestingly enough, this chain breaking also makes the search by ElementName broken.

For example, place a FrameworkElement inside a binding’s ConverterParameter property, and try to bind one of the element’s properties. VS will write in its output window the error message above.
You can place the element like this:
<Button.Content>
    <Binding Converter="{StaticResource someConverter}">
        <Binding.ConverterParameter>
            <!–Here is the binding that shouldn’t work: –>
            <FrameworkElement DataContext="{Binding ElementName=myElement, Path=Content}"/>
        </Binding.ConverterParameter>
    </Binding>
</Button.Content>

You can overcome this problem by using the x:Reference markup extension (or its improved version I wrote about in one of my previous posts). You can a name to the element you want to bind to, and then let the binding engine find it by using the Source property, like this:

{Binding Source={x:Reference myElement}, Path=Width}

How can you name your target element? You can simply use the x:Name directive, or the more elegant "Name" property, which is mapped to the x:Name directive by FrameworkElement with the RuntimeNamePropertyAttribute attribute.

Advertisements