【发布时间】:2017-03-13 17:14:43
【问题描述】:
在 msdn 中您可以阅读:“初始化包含从指定列表复制的元素的 ObservableCollection 类的新实例。”
但我不明白这种行为:
我有一个类 Person。
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public override string ToString()
{
return Firstname + " " + Lastname;
}
}
现在我创建一个人员列表。 然后我创建一个 ObservableCollection,它应该包含列表中复制的元素。
然后我更改列表中的一个人,以及 ObservableCollection 中的一个人。 这两个更改都反映在两个集合中。为什么?
最后,我将一个人添加到列表中,并将一个人添加到 OC。 添加的项目仅反映在相关集合中
public partial class MainWindow : Window
{
private List<Person> PersonList{ get; set; }
private ObservableCollection<Person> PersonObservableCollection { get; set; }
public MainWindow()
{
InitializeComponent();
FillCollections();
listbox1.ItemsSource = PersonList;
listbox2.ItemsSource = PersonObservableCollection;
}
private void FillCollections()
{
PersonList = LoadDataPerson();
PersonObservableCollection = new ObservableCollection<Person>(PersonList);
// Adding a person to the List.
PersonList.Add(new Person() { Firstname = "added to List",});
// Adding a person to the ObservableCollection.
PersonObservableCollection.Add(new Person() { Firstname = "added to Observable Collection" });
// Changing then name of the first person in the List
Person p1 = PersonList[0];
p1.Lastname = "changed in List";
// Changing the name of the second person in the ObservableList
Person p2 = PersonObservableCollection[1];
p2.Lastname = "changed in ObservableCollection";
}
private List<Person> LoadDataPerson()
{
List<Person> personen = new List<Person>();
personen.Add(new Person() { Firstname = "John"});
personen.Add(new Person() { Firstname = "Will"});
personen.Add(new Person() { Firstname = "Sam" });
return personen;
}
}
xaml:
<Window x:Class="ObservableCollection.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:ObservableCollection"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" x:Name="listbox1"/>
<ListBox Grid.Column="1" x:Name="listbox2"/>
</Grid>
输出如下所示: Output
【问题讨论】:
-
您了解reference types 的工作原理吗?特别是,您是否了解引用类型对象的列表实际上是对存在于内存中其他位置的唯一可识别对象的引用列表?