简体   繁体   中英

WPF Datagrid binding and column display

I have datatable as Item source for DataGrid, this datatable has lots of columns. Is it possible to display few columns instead all of them without creating a new table?

Yes, it is. Just mark AutoGenerateColumns=False and manually define your columns. You can use normal text-bound columns, checkbox columns, custom XAML template columns and more, as you can see in the documentation .

<DataGrid ItemsSource="{Binding DataSource}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
    <DataGridTextColumn Header="Simple Value"
                      Binding="{Binding SimpleValue}" Width="*" />
     <DataGridTemplateColumn Width="*" Header="Complex Value">
        <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
            <StackPanel>
               <TextBox Text="{Binding ComplexValue}"/>
               <TextBox Text="{Binding ComplexValue2}"/>
            </StackPanel>
          </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
  </DataGrid>

Also, you can handle DataGrid.AutoGeneratingColumn event and set e.Cancel = true for columns that you don't want to be shown. This way you don't have to manually define columns that you want to show.

Yes, Yes very much. If your Table structure and Column Name remains constant then in Datagrid XAML set AutoGenerateColums = False and manually create all columns.

<dg:DataGrid Name="mydg" ItemsSource="{Binding Data}" AutoGenerateColumns="False">
 <dg:DataGrid.Columns>
  <dg:DataGridTextColumn Header="Col 0" Binding="{Binding FirstColumnName}" />
  <dg:DataGridTextColumn Header="Col 1" Binding="{Binding SecondColumnName}" />
 </dg:DataGrid.Columns>
</dg:DataGrid>

and then in codebehind simple provide Source like

mydg.ItemSource = Data.DefaultView;

Now when your DataTable contains column FirstColumnName and SecondColumnName they will be databound to your Datagrid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM