gpt4 book ai didi

c# - 为什么 IEnumerable 需要调用 ToList 来更新 ListView ?

转载 作者:行者123 更新时间:2023-11-30 14:03:40 26 4
gpt4 key购买 nike

我相信对此有很好的解释。我猜这与我感冒和遗漏一些明显的东西有关......

我有一个简单的窗口:

<Window x:Class="WpfIdeas.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:w="clr-namespace:WpfIdeas"
Title="Window1" Height="300" Width="315">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" x:Name="btnAddObject" Click="btnAddObject_Click">Add Object</Button>
<ListView Grid.Row="1" ItemsSource="{Binding Objects}">
</ListView>
</Grid>
</Window>

窗口后面的代码是:

using System.Windows;

namespace WpfIdeas
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new ObjectVM();
}

private void btnAddObject_Click(object sender, RoutedEventArgs e)
{
(DataContext as ObjectVM).AddObject();
}
}
}

并且它的 DataContext 被设置为以下类:

class ObjectVM : INotifyPropertyChanged
{
private readonly List<ObjectModel> objects = new List<ObjectModel>();

//public IEnumerable<ObjectModel> Objects { get { return objects } } //doesn't work
public IEnumerable<ObjectModel> Objects { get { return objects.ToList() } } //works

private Random r = new Random();

public void AddObject()
{
ObjectModel o = new ObjectModel(r);
objects.Add(o);
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Objects"));
}
}

public event PropertyChangedEventHandler PropertyChanged;
}

ObjectModel 类实际上是一个结构,在实例化时会生成一个 14 个字符的字符串。 ToString() 方法只是输出这个字符串。

如上代码所示,当我单击“添加对象”按钮时,ListView 中会出现一个新字符串。

但是,如果我删除 Objects 属性中的 ToList() 调用,ListView 中将不会显示任何内容。它只是保持空白。

这是为什么?

最佳答案

Using Collection Objects as a Binding Source :

您可以枚举任何实现 IEnumerable 接口(interface)的集合。但是,要设置动态绑定(bind)以便集合中的插入或删除自动更新 UI,集合必须实现 INotifyCollectionChanged 接口(interface)。此接口(interface)公开了一个事件,该事件必须在基础集合发生更改时引发。

关于c# - 为什么 IEnumerable<T> 需要调用 ToList 来更新 ListView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3726665/

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