将 DataGrid 的 ItemsSource 绑定到列表

Jen*_*ens 5 c# wpf binding datagrid

List我正在尝试在 a和 a之间创建绑定DataGrid。我还没有在网上找到有效的解决方案,这很奇怪。

在我的小例子中,我创建了一个具有两个属性和 的List对象:publicAgeName

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

public ObservableCollection<Person> Collection { get; set; } 

public List<Person> Persons { get; set; }

private void WindowLoaded(object sender, RoutedEventArgs e)
{

    this.Persons = new List<Person>();

    for (int i = 0; i != 35; i++)
    {
        this.Persons.Add(new Person() {Age = i, Name = i.ToString()});
    }

    this.Collection = new ObservableCollection<Person>(this.Persons);
}
Run Code Online (Sandbox Code Playgroud)

XAML 代码如下所示:

<Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
    <DataGrid x:Name="DataGrid" ItemsSource="{Binding Collection}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

或这个(两者都不起作用):

<Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
        <DataGrid x:Name="DataGrid" ItemsSource="{Binding Persons}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

如果我使用,this.DataGrid.ItemsSource = this.Persons;我至少会看到列表中的所有项目,但this.DataGrid.Items.Refresh()每次源List更改时我都必须这样做,这就是我问这个问题的原因:

我究竟做错了什么?我需要实施吗INotifyPropertyChanged

这个问题一定很容易回答,但理解其中的机制也很棒。

d.m*_*ada 5

好的,所以您遇到问题的原因是加载窗口时发生的情况以及数据绑定的设置方式。

在窗口已经加载之前,DataGrid 的 ItemsSource 不会发生(它在窗口加载事件中设置)。因此,DataGrid 现在不会发现它的 ItemsSource 已更改。您可以通过将更改的 INotiftyProperty 添加到列表本身来解决此问题,或者,您可以先创建 DataGrid 列表,然后在加载窗口时填充。

例如:

xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        Collection = new ObservableCollection<Person>();
        InitializeComponent();
    }

    public class Person
    {
        public string Name { get; set; }

        public int Age { get; set; }
    }

    public ObservableCollection<Person> Collection { get; set; }

    public List<Person> Persons { get; set; }

    private void WindowLoaded(object sender, RoutedEventArgs e)
    {

        this.Persons = new List<Person>();

        for (int i = 0; i != 35; i++)
        {
            this.Persons.Add(new Person() { Age = i, Name = i.ToString() });
        }

        foreach (var p in Persons)
        {
            Collection.Add(p);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

xml:

<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"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        x:Name="TestWindow"
        Loaded="WindowLoaded">
    <Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
        <DataGrid x:Name="DataGrid" ItemsSource="{Binding Collection}" />
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)