I am using the DataGrid control from Windows Community Toolkit for UWP, but I can't find a solution to dynamically hide or show columns.
Runtime error: Failed to assign to property 'Microsoft.Toolkit.Uwp.Ui.Controls.DataGridColumn.Visibility'
<controls:DataGrid x:Name="TradeGrid">
<controls:DataGridTextColumn
x:Uid="DataColumnPositionContract"
Width="SizeToCells"
Binding="{Binding Path=TradePosition.Contract.Name}"
Tag="Contract"
Visibility="{Binding ElementName=TradeGrid, Path=DataContext.IsContractVisible, Converter={StaticResource BoolToVisConv}}" />
</controls:DataGrid>
The view model structure looks like:
PageViewModel (bound to page)
ItemViewModel (DataContext of a column)
The converter is the converter provided by the toolkit. The boolean property to bind is not part of the DataContext of the column (ItemViewModel). I need to access the parent view model (PageViewModel) to get the property.
Can anyone give me a hint on how to bind to the Visibility
property of a DataGridColumn?
I am open for other solutions if the binding is not possible this way in UWP.
Thanks!
Firstly, I cannot reproduce the Runtime error based on the code provided by you.
Secondly, the Visibility
property of DataGridTextColumn
is not a dependency property from the source code, so the binding will not work.
So, you could try to set the value of Visibility
property to Visibility.Collapsed
or Visibility.Visible
directly when you know the target columns to hide or show.
Update:
If you want to set the Visibility
property directly, you need to know the index(such as the “0”) of the target column and write the code in a method in code-behind such as a Click
event handler on a button, like this:
dataGrid1.Columns.ElementAt(0).Visibility = Visibility.Visible;
You can use {x:Bind} extension instead of {Binding} extension to show or hide columns in a DataGrid
, and the binding source class need to implement System.ComponentModel.InotifyPropertyChanged, like this
<controls:DataGridTextColumn
…… Visibility="{x:Bind SourceClass.Visible,Mode=OneWay}" />
You can change the value of SourceClass.Visible
to show or hide a column at runtime.