Wednesday, April 15, 2015

Cannot find governing FrameworkElement or FrameworkContentElement for target element

I wrote this blog entry because I am fed up with having to remember the solution from scratch every time I get this error message. I happens whenever I try to set the ItemSource for a DataGridComboBoxColumn. Because data grid columns are not in the Visual Tree they don't inherit the data context from the page.

So the XAML below will always fail and you will see "Cannot find governing FrameworkElement or FrameworkContentElement for target element" in the output window. The problem is that the ItemsSource has no DataContext to work in.

<DataGridComboBoxColumn Header="Owner" Width="100" ItemsSource="{Binding Path=Owners}" DisplayMemberPath="OwnerName" SelectedValuePath="OwnerID" SelectedValueBinding="{Binding Path=OwnerID}"></DataGridComboBoxColumn>


There are many solutions out there on the web, but the easiest and most logical for me is to create a CollectionViewSource resource and reference that. To implement the XAML above, simply add the resource...

<Page.Resources>
    <CollectionViewSource x:Key="Owners" Source="{Binding Owners}"/>
</Page.Resources>

... and change the ItemsSource...

ItemsSource="{Binding Source={StaticResource Owners}}"

1 comment:

  1. This is a great solution! All of the other work-arounds for this were so much more complicated.

    ReplyDelete