In your XAML, bind your datagrid to an ObservableCollection of objects of a particular class that has properties.
XAML:
<WpfToolkit:DataGrid x:Name="MyDataGrid" ItemsSource="{Binding Path=Collection}" HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" CanUserSortColumns="False" AutoGenerateColumns="False" RowHeaderWidth="25" RowHeight="25"/>
Then you can create your columns programmatically in C # / VBA and bind each individual column to a class property to which the ObservableCollection contains its objects. By adding class objects, you add rows to the datagrid. In other words, each class object in an ObservableCollection will be a row, and the class properties will be columns.
Here is an example of how to programmatically bind your columns ... C #:
ObservableCollection<IData> datagridData = new ObservableCollection< IData >(); Binding items = new Binding(); PropertyPath path = new PropertyPath("Name"); // 'Name' is actually the name of the variable representing the property items.Path = path; MyDataGrid.Columns.Add(new DataGridTextColumn() { Header = "Names", Width = 275, Binding = items }); //repeat the creation of columns //... //- Add some objects to the ObservableCollection //- Then bind the ItemsSource of the datagrid to the ObservableCollection datagridData .Add(new Data("Bob", string.Empty)); MyDataGrid.DataContext = new DataModel{ MyData = datagridData };
* Editing: Sorry for that! Here's how you can achieve the same thing in XAML:
<WpfToolkit:DataGrid x:Name="MyDataGrid" ItemsSource="{Binding Path=Collection}" HorizontalScrollBarVisibility="Hidden" SelectionMode="Extended" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" CanUserSortColumns="False" AutoGenerateColumns="False" RowHeaderWidth="25" RowHeight="25"> <WpfToolkit:DataGridTextColumn Header="Names" Width="2*" Binding="{Binding Path=Name}"/> <WpfToolkit:DataGridTextColumn Header="Names" Width="2*" Binding="{Binding Path=Age}"/> </WpfToolkit:DataGrid.Columns> </WpfToolkit:DataGrid>
Edit 2: This is what the ObservableCollection and class code looks like in C #:
public class DataModel { public ObservableCollection<IData> MyData{ get; set; } } public interface IData { string Name{ get; set; } string Age{ get; set; } } public class Data : IData { public Data(string name, string age) { Name= name; Age= age; } public string Name{ get; set; } public string Age{ get; set; } }
source share