Wpf – Binding in WPF style causes inexplicable “Cannot find governing FrameworkElement” error

bindingdata-bindingwpfxaml

I have an ItemsControl that displays a bunch of rectangles. Each rectangle needs to be offset upward and to the left. So, I created a RectangleStyle that uses bindings to set the width, height, X translation, and Y translation for a rectangle.

The width and height bindings are working fine, but I'm getting the following error for the TranslateTransform bindings:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Offset.X; DataItem=null; target element is 'TranslateTransform' (HashCode=16452547); target property is 'X' (type 'Double')

Here is the definition of my ItemControl:

<ItemsControl
    Style="{StaticResource ItemsControlStyle}"
    ItemsSource="{Binding Zones}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Rectangle Style="{StaticResource RectangleStyle}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Here is the definition of ItemsControlStyle:

<Style x:Key="ItemsControlStyle" TargetType="ItemsControl">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style>
                <Setter Property="Canvas.Left" Value="{Binding Point.X}" />
                <Setter Property="Canvas.Top" Value="{Binding Point.Y}" />
            </Style>
        </Setter.Value>
    </Setter>
</Style>

And here is the definition of RectangleStyle:

<Style x:Key="RectangleStyle" TargetType="Rectangle">
    <Setter Property="Width" Value="{Binding Size.Width}" />
    <Setter Property="Height" Value="{Binding Size.Height}" />
    <Setter Property="RenderTransform">
        <Setter.Value>
            <!-- these bindings are causing the error -->
            <TranslateTransform X="{Binding Offset.X}" Y="{Binding Offset.Y}" />
        </Setter.Value>
    </Setter>
</Style>

The two bindings in the RenderTransform setter of RectangleStyle are the cause of the error, but I'm not sure what to do to fix the problem. Interestingly, the graphics are being translated properly, so WPF is able to resolve the bindings–it's just not happy about them for some reason.

What can I do to fix the bindings?


Edit

I submitted a bug report on MS Connect:

https://connect.microsoft.com/VisualStudio/feedback/details/746840/misleading-cannot-find-governing-frameworkelement-error-message-appears-in-output-window

Best Answer

I also cannot explain why the error message happens, but I have found out that adding an x:Name property to the transform is a way to get rid of the error message:

<TranslateTransform x:Name="myTransform" X="{Binding Offset.X}" Y="{Binding Offset.Y}" /> 
Related Topic