Alex Rivera | Logout

WPF Binding to ElementName inside ItemsControl

Asked 2010-09-20T17:08:38.467
11

I have a checkbox, and an ItemsControl populating several DataGrids the following way:

<Checkbox Content="Birthday Column Visible" x:Name="UI_BirthdayVisibleCB" />

<ItemsControl  ItemsSource="{Binding Path=ParentsCollection}">
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <DataGrid  AutoGenerateColumns="False" ItemsSource="{Binding Children}">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Birthday" Width="120" Visibility="{Binding IsChecked, ElementName=UI_BirthdayVisibleCB, Converter={StaticResource BoolToVis}}" >
...
               </DataGridTemplateColumn>
            </DataGrid.Columns>
         </DataGrid>
</Rest of closing tags>

This creates binding output errors as it tries to find IsChecked on the DataGridTemplateColumn. If I try to search for a Relative Ancestor I receive the exception:

Binding.RelativeSource cannot be set while using Binding.ElementName.

I have a ViewModel, and stick to MVVM mostly, but in this case I'd really like to keep the column visibilities on the View layer. Note that BoolToVis just converts Boolean to Visibility.

Edit

Here is an example of what I'm trying to do:

 <DataGridTemplateColumn Header="Birthday" Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyView} }, Path=IsChecked, ElementName=UI_BirthdayVisibleCB, Converter={StaticResource BoolToVis}}" />

It compiles but doesn't run however, it throws the exception above.

Edit
Report

1 Answer

3

If you want to try RelativeSource, you have to remove ElementName from the declaration:

However, only one of the three properties, ElementName, Source, and RelativeSource, should be set for each binding, or a conflict might occur. This property throws an exception if there is a binding source conflict.

http://msdn.microsoft.com/en-us/library/system.windows.data.binding.elementname.aspx

Your usage of ElementName seems correct, so I'll continue to look at the problem if you prefer that over RelativeSource.

answered 2010-09-20T18:29:47.867

Your Answer