c# - 为什么我的 C# 代码不能添加到列表中并显示它?

标签 c# wpf list addressbook

我正在尝试自学 C#,但在使用这段代码时遇到了问题:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            contacts.Add(new Contact()
                {
                Name = "James",
                Email = "james@mail.com",
                PhoneNumber = "01234 111111"
            });
            contacts.Add(new Contact()
            {
                Name = "Bob",
                Email = "bob@mail.com",
                PhoneNumber = "01234 222222"
            });
            contacts.Add(new Contact()
            {
                Name = "Emma",
                Email = "emma@mail.com",
                PhoneNumber = "01234 333333"
            });
        }
        protected List<Contact>  contacts = new List<Contact>();

        public List<Contact> Contacts
        {
            get { return  contacts; }
            set {  contacts = value; }
        }

        private void NewContactButton_Click(object sender, RoutedEventArgs e)
        {
            contacts.Add(new Contact()
            {
                Name = NameTextBox.Text,
                Email = EmailTextBox.Text,
                PhoneNumber = PhoneTextBox.Text
            });
        }

        }

    }

它没有在列表中显示新联系人,我不确定它是否正在创建新联系人。它显示前三个非常好。

我觉得我漏掉了一些重要的东西。

最佳答案

改变

   protected List<Contact>  contacts = new List<Contact>();

    public List<Contact> Contacts
    {
        get { return  contacts; }
        set {  contacts = value; }
    }

protected ObservableCollection<Contact> contacts = new ObservableCollection<Contact>();

public ObservableCollection<Contact> Contacts
{
    get { return contacts; }
    set { contacts = value; }
}

并在代码顶部添加 using System.Collections.ObjectModel;

并对其余代码进行必要的更改。

关于c# - 为什么我的 C# 代码不能添加到列表中并显示它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13372164/

相关文章:

C# 停止一次又一次调用 MDI 子项

wpf - 如何在 WPF dataGrid 中的 TAB 键上添加新行

wpf - 在 WPF 中更改 Alpha 混合模式?

c# - 对于通过反射找到的属性,我如何测试 Listness 并对其进行枚举?

list - Lisp:列表与 S 表达式

python parse 仅打印列表中的第一行

c# - 如何从 C# 中的 SQL 存储过程中检索结果集和 PRINT 消息?

c# - 覆盖 WebControl 上的控件集合

c# - 如果 MySQL 表中的字段为空,则更新该字段

wpf - 将系统焦点设置在我的应用程序上