Typically in WPF, you would leverage an ObservableCollection<>
Because then you can just .Add()
/ .Remove()
elements to/from the source collection, and any controls bound (Data Binding) automatically get updated (Automatic Property Change Notification). Those are 2 important concepts in WPF.
Main Window View Model
using System.Collections.Generic;
namespace TestDatagrid345.ViewModels
{
class Window1ViewModel
{
private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers
{
Get { return _customers; }
}
}
}
Main Window
using System.Collections.Generic;
using System.Windows;
namespace TestDatagrid345
{
public partial class Window1 : Window
{
Window1ViewModel _viewModel;
public Window1()
{
InitializeComponent();
_viewModel = (Window1ViewModel)this.DataContext; // @#$% (see XAML)
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// but this stuff could instead be done on a 'Submit' button click on form:
_viewModel.Customers.Add(new Customer { FirstName = "Tom", LastName = "Jones" });
_viewModel.Customers.Add(new Customer { FirstName = "Joe", LastName = "Thompson" });
_viewModel.Customers.Add(new Customer { FirstName = "Jill", LastName = "Smith" });
}
}
}
Main Window XAML
<Window
x:Class="TestDatagrid345.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:TestDatagrid345.ViewModels"
Title="Window1"
Height="350"
Width="525"
WindowState="Maximized">
<Window.DataContext>
<vm:Window1ViewModel /> <!-- this needs to be here for @#$% -->
</Window.DataContext>
<Grid>
<DataGrid
AutoGenerateColumns="True"
ItemsSource="{Binding Path=Customers}"
AlternatingRowBackground="LightBlue"
AlternationCount="2" />
</Grid>
</Window>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…