Hide Datagrid Column based on its Property name

2020-02-15 03:38发布

I have a DataGrid defined as follows :

<DataGrid Name="dtMydatagrid" Margin="10,10,10,10" RowHeight="20" AutoGenerateColumns="True" ItemsSource="{Binding}" Height="auto" Width="auto">
   <DataGrid.Columns>
      <DataGridTemplateColumn Header="">
         <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
               <TextBox x:Name="TXT" Background="Transparent" Width="15" IsReadOnly="True" Visibility="Hidden" Margin="0,0,0,0"/>
               <DataTemplate.Triggers>
                  <DataTrigger Binding="{Binding Path=IsBKM}" Value="true">
                     <Setter Property="Background" Value="AQUA" TargetName="TXT"/>
                     <Setter Property="Visibility" Value="Visible" TargetName="TXT"/>
                  </DataTrigger>
               </DataTemplate.Triggers>
            </DataTemplate>
         </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
   </DataGrid.Columns>
</DataGrid>

Now, I have a boolean property in my class named IsBKM to which the DataGridTemplateColumn is bounded. So, it is displayed by as CheckBox. I don't want to display the IsBKM column in my DataGrid. Can I use a trigger and hide the column whose name is IsBKM or any different solution?

Thanks in advance.

1条回答
【Aperson】
2楼-- · 2020-02-15 04:04

You could handle the DataGrid.AutoGeneratedColumns Event and set the column's Visibility property from there. You should be able to do something like this:

private void DataGridAutoGeneratingColumn(object sender, 
    DataGridAutoGeneratingColumnEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    if (dataGrid != null && IsBKM) dataGrid.Columns[0].Visible = false;
}

UPDATE >>>

You can use the e.Column.Header property to check the name of the column and then use that instead. However, your column has no Header currently set. You could also set the column name (in XAML) and then check for that Name value instead of using the Header property:

private void DataGridAutoGeneratingColumn(object sender, 
    DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.Column.Name == "IsBKM" && IsBKM)
    {
        e.Column.Visibility = Visibility.Collapsed;
    }
}
查看更多
登录 后发表回答