gpt4 book ai didi

c# - 将 DataGrid 的 ItemsSource 绑定(bind)到列表

转载 作者:行者123 更新时间:2023-11-30 20:41:31 29 4
gpt4 key购买 nike

我正在尝试在 ListDataGrid 之间创建绑定(bind)。我还没有在网上找到一个非常奇怪的有效解决方案。

在我的小示例中,我创建了一个对象的 List,它具有两个 public 属性 AgeName:

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);
}

XAML 代码如下所示:

<Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
<DataGrid x:Name="DataGrid" ItemsSource="{Binding Collection}" />
</Grid>

或者这个(两者都不工作):

<Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
<DataGrid x:Name="DataGrid" ItemsSource="{Binding Persons}" />
</Grid>

如果我使用 this.DataGrid.ItemsSource = this.Persons; 我至少会看到列表中的所有项目,但我必须 this.DataGrid.Items.Refresh() 每次 Source List 发生变化,这就是我问这个问题的原因:

我做错了什么?我是否需要实现 INotifyPropertyChanged

这个问题一定很容易回答,但如果能理解其中的原理也很棒。

最佳答案

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

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

例如:

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);
}
}
}

xaml:

<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>

关于c# - 将 DataGrid 的 ItemsSource 绑定(bind)到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32257785/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com