Posted By

heathbo on 09/27/13


Tagged


Versions (?)

WPF DataGrid


 / Published in: C#
 

Bind and link to a DataGrid.

You first must have a source of data to bind to a DataGrid. For this were using an ObservableCollection of BoxSizes objects.

We are using a DataGrid titled boxGrid;

Note: Use ObservableCollection instead of List because any changes made to the ObservableCollection will automatically be shown in the DataGrid. Not so with List.

  1. In the XAML:
  2.  
  3. <DataGrid x:Name="boxGrid" Margin="0,377,0,0" Width="328" VerticalAlignment="Top" Height="135" AutoGenerateColumns="False">
  4. <DataGrid.Columns>
  5. <DataGridTemplateColumn Width="65">
  6. <DataGridTemplateColumn.CellTemplate>
  7. <DataTemplate>
  8. <Grid>
  9. <Button Content="Delete" Width="50" Click="DeleteBox"/>
  10. </Grid>
  11. </DataTemplate>
  12. </DataGridTemplateColumn.CellTemplate>
  13. </DataGridTemplateColumn>
  14. <DataGridTextColumn Header="Box Size" Binding="{Binding boxSize}" Width="150"/>
  15. <DataGridTextColumn Header="Weight" Binding="{Binding weightString}" Width="*"/>
  16. </DataGrid.Columns>
  17. </DataGrid>
  18.  
  19.  
  20. In the Code Behind:
  21.  
  22.  
  23. ObservableCollection<BoxSizes> boxList = new ObservableCollection<BoxSizes>();
  24.  
  25. BoxSizes boxS = new BoxSizes("5x5x5");
  26. boxList.Add(boxS);
  27.  
  28. boxGrid.ItemsSource = boxList;
  29.  
  30.  
  31.  
  32. public class BoxSizes
  33. {
  34. public string boxSize { get; set; }
  35.  
  36. public BoxSizes(string bSize)
  37. {
  38. boxSize = bSize;
  39. }
  40. }
  41.  
  42.  
  43. NOTE: The DataGrid example above is a more detailed and exhaustive example. A simpler version would be:
  44.  
  45. In the XAML:
  46. <DataGrid x:Name="boxGrid" Margin="11,158,9,0" VerticalAlignment="Top" Height="152" Foreground="#FF001881"/>
  47.  
  48. In this version, the columns and headers are automatically created based on the BoxSizes class.

Report this snippet  

You need to login to post a comment.