I have a datagrid whose ItemsSource
binds to a CollectionViewSource
.
In each column I specify the Path
property of the binding to get the specific information to display.
What I'd like to do is toggle some of the columns with a checkbox if the user wants more info. To do this, I need to bind the visibility property to the value of the checkbox (with a converter) but I'm pretty sure the data context of the column is interfering with the binding.
<DataGrid ItemsSource="{Binding Source={StaticResource cvs}}" ....>
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}"
Visibility="{Binding IsChecked,
ElementName=IncludeFullHist,
Converter={StaticResource boolItemsConverter}}"/>
</DataGrid.Columns>
</DataGrid>
I need the checkbox in my viewmodel as well, so I have its IsChecked
property bound to a property on my ViewModel
<CheckBox x:Name="IncludeFullHist" IsChecked="{Binding Path=ManagerFullHist }" />
For other elements in my page, I've been able to hook up visibility bindings with either of the two following methods, but neither seem to work when I copy them over into the datagrid:
<TextBlock DockPanel.Dock="Left" Text=" Visible 2 "
Visibility="{Binding Path=DataContext.ManagerFullHist,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}},
Converter={StaticResource boolItemsConverter}}"/>
<TextBlock DockPanel.Dock="Left" Text=" Visible 3 "
Visibility="{Binding Path=ManagerFullHist,
Source={StaticResource mainWinResource},
Converter={StaticResource boolItemsConverter}}"/>
Any suggestions on ways that I can solve this in the datagrid?
Please let me know if I've omitted any code that could be potentially helpful.
The
DataGridColumn
is not actually part of theVisualTree
, so bindings on the class cannot find their sourceYou can set things like the
Visibility
andWidth
property in theCellStyle
orHeaderStyle
of theDataGridColumn
, although that isn't quite the same.The closest I've found to a solution would be to create a Freezable object in your
<DataGrid.Resources>
that stores the binding, then use thatStaticResource
in theVisibility
binding. It's not a pretty solution, but it's the only one I can find at this time.You can view of an example of it here