Hide Datagrid Column based on its Property name

安稳与你 提交于 2019-12-29 09:17:10

问题


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:


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;
    }
}


来源:https://stackoverflow.com/questions/21231803/hide-datagrid-column-based-on-its-property-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!