WPF Datagrid binding and column display

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.

Tags:

C#

Wpf