Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

wpf - Hide Datagrid Column based on its Property name

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...