1
votes

I have a DataGrid bound to a ViewModel's property of type ObservableCollection. Inside DataGrid I have several DataGridTextColumns bound to item of the ObservableCollection. I need to access parent DataContext (ViewModel) to set Visibility property of one of the DataGridTextColumns. There is a solution suggested over the internet:

{Binding DataContext.IsColumnVisible, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyControl}}}

IsColumnVisible property is of type System.Windows.Visibility. Such solution works for other properties like DataGridTextColumn.Binding, but doesn't for DataGridTextColumn.Visibility! Is there solution for Visibility?

EDIT: I finally adopted the following solution: Bind datagrid column visibility MVVM

3

3 Answers

2
votes

DataGrid-columns are abstract objects, you cannot target them using ElementName (lacking namescope) or RelativeSource (not in the visual tree).

Additionally DataGrid-columns have no DataContext...

0
votes

You can use a BooleanToVisibilityConverter to convert the Parent's Visibility property to a Boolean value.

http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter.aspx

0
votes

Bind the Visibility property of your column to a property of your view model. See the following SA question.

Another thing is: use the BooleanToVisibilityConverter class. It's not good your view model exposes a property of a type (Visibility) that is closely tied to the view. This introduces a coupling between your view and your view model that should be avoided.

Exposes a bool, then let the view adapts itself to its view model using the converter.