我与这里的数据使用此代码结合试验:WPF:会发生什么列表<T>而不是ObservableCollection <T>用于数据绑定?
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace KhoaOOP6
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// LOOK AT THIS!!! This is the data; if you use only List the application will break
ObservableCollection<Student> studentGroup = new ObservableCollection<Student>()
{
new Student("Jaakko Laaksonen", "Sammonkatu 5", new DateTime(1995,11,23)),
new Student("Kaarina Helin", "Tullikatu 7", new DateTime(1970,01,09)),
new Student("Maria Nyman", "Adlercreutzinkatu 33", new DateTime(1980,02,24)),
new Student("Liisa Danielsson", "Askolinintie 5", new DateTime(1981,05,26)),
new Student("Aino Henriksson", "Caloniuksenkatu 12", new DateTime(1971,10,07)),
new Student("Elsi Gustafsson", "Haukantie 21", new DateTime(1972,11,11)),
new Student("Henri Mattsson", "Jakarinkatu 18", new DateTime(2003,12,17)),
new Student("Emili Ojala", "Karhupolku 29", new DateTime(1967,04,30)),
new Student("Sinikka Jokinen", "Kolavuorenkuja 32", new DateTime(1969,08,15)),
new Student("Aurora Niemi", "Laamanninpolku 39", new DateTime(1989,09,20))
};
public MainWindow()
{
InitializeComponent();
// Do our binding business
// Create a new binding
Binding myNewBindDef = new Binding()
{
Mode = BindingMode.OneWay,
Source = studentGroup
};
// LOOK AT THIS!!!!!!!!!!!!!!!
BindingOperations.SetBinding(studentGrid, DataGrid.ItemsSourceProperty, myNewBindDef);
}
private void AddNewBtn_Click(object sender, RoutedEventArgs e)
{
// Create a new Student:
Student newStudent = new Student(NameTxtBox.Text, AddressTxtBox.Text, DateTime.Parse(DobTxtBox.Text));
//Add to database
studentGroup.Add(newStudent);
}
}
}
它工作正常的现在,但也有一些事情我不明白:
问题1:如果我使用(List studentGroup)而不是(ObservalbeCollection studentGroup),UI最初正确显示列表。但是,当我修改studentGroup列表时,应用程序突然崩溃。为什么?
问题2:即使比怪异,应用仅在发布模式坠毁,当我切换到调试模式追查错误,它不会崩溃。为什么?如果我事先不知道ObservableCollection会怎么样,我将如何跟踪这些错误?
*编辑:对不起,我没有更清楚这样说:Visual Studio中并没有告诉我发生的任何异常,我想调试会做什么,但它并没有崩溃,所以...
请写出异常信息 – Jacek
如果程序崩溃,这是代码问题,而不是列表。发布例外。没有什么能够阻止你使用'List '并且在改变时引发NotifyPropertyChanged事件。 –
有没有例外的消息可以说,它只是突然崩溃。正如我试图调试以查看异常实际是什么,但它并没有崩溃。这就是为什么我问,而不是谷歌的第一个例外。 –