This is the simplest version to create a table that would look like your image. You would use styles to style the columns and headers (e.g. header background).
A TableRowData
iteme is displayed as a row in the DataGrid
.
Each property of this TableRowData
type is displayed as a row's column inside the DatGrid
.
class TableRowData : INotifyPropertyChanged
{
private int serialNumber;
public int SerialNumber
{
get => this.serialNumber;
set
{
this.serialNumber = value;
OnPropertyChanged();
}
}
private int columnOne;
public int ColumnOne
{
get => this.columnOne;
set
{
this.columnOne= value;
OnPropertyChanged();
}
}
private int columnTwo;
public int ColumnTwo
{
get => this.columnTwo;
set
{
this.columnTwo= value;
OnPropertyChanged();
}
}
private int columnThree;
public int ColumnThree
{
get => this.columnThree;
set
{
this.columnThree= value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke();
}
}
ViewModel.cs
class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
this.TableRows = new ObservableCollection<TableRowData>();
}
// Adding a new TableRowData to the ObservableCollection will immediately add a row to the bound DataGrid
public void AddRow()
{
this.TableRows.Add(new TableRowData());
}
private ObservableCollection<TableRowData> tableRows;
public ObservableCollection<TableRowData> TableRows
{
get => this.tableRows;
set
{
this.tableRows= value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke();
}
}
MainWindow.xaml
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContext>
<StackPanel>
<Button Click="OnAddButtonClicked" Content="Add Row" />
<DataGrid ItemsSource="{Binding TableRows}" />
</StackPanel>
</Window>
MainWindow.xaml.cs
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnAddButtonClicked(object sender, RoutedEventArgs e)
{
(this.DataContext as ViewModel)?.AddRow();
}
}
Ideally you would use a ICommand
instead of the Button.Click
event handler to invoke the AddRow()
method.