My WPF is a bit rusty, but I would suggest that you set the window's DataContext
to a view model instance and set the DataGrid
Items source to a CustomerList
property defined in the view model. So the Xaml would look like this:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:TestViewModel />
</Window.DataContext>
<Grid>
<DataGrid x:Name="DataGrid" ItemsSource="{Binding CustomerList}" AutoGenerateColumns="True" />
</Grid>
</Window>
The view model could be simply defined as:
public class TestViewModel
{
public List<Customer> CustomerList { get; set; }
public TestViewModel()
{
CustomerList = Customer.GetSampleCustomerList();
}
}
I would include the Customer
class as in the example but update the GetSampleCustomerList
method so that it uses C#12 syntax.
public static List<Customer> GetSampleCustomerList()
{
return [
new("A.", "Zero",
"12 North Third Street, Apartment 45",
false, true),
new("B.", "One",
"34 West Fifth Street, Apartment 67",
false, false),
new("C.", "Two",
"56 East Seventh Street, Apartment 89",
true, null),
new("D.", "Three",
"78 South Ninth Street, Apartment 10",
true, true)
];
}