WPF Datagrid binding and column display

前端 未结 3 2095
死守一世寂寞
死守一世寂寞 2021-01-04 01:33

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?

相关标签:
3条回答
  • 2021-01-04 02:06

    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.

    0 讨论(0)
  • 2021-01-04 02:21

    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.

    0 讨论(0)
  • 2021-01-04 02:30

    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>
    
    0 讨论(0)
提交回复
热议问题