1

我正在尝试自学 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
            });
        }

        }

    }

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

我有一种感觉,我遗漏了一些重要的东西。

4

2 回答 2

5

改变

   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;到代码的顶部。

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

于 2012-11-14T02:38:01.437 回答
1

使用下面提到的代码,它将起作用:

public MainWindow()
    {
        InitializeComponent();
        dgContacts.ItemsSource = Contacts;
    }

    private void btnClick_Click(object sender, RoutedEventArgs e)
    {
        Contacts.Add(new contact()
        {
            Name = "Person",
            Email = "Person Address",
            PhoneNumber = "Person Ph"
        });

    }

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

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

并且此代码的​​ xaml 将是:

<DataGrid Name="dgContacts" Margin="5" AutoGenerateColumns="True" ItemsSource="{Binding}"></DataGrid>

WPF 的主要部分是绑定,如果你正确地进行绑定,它将为你创造魔法。如果此代码适合您;我将向您展示另一种绑定它的方法。

于 2012-11-14T08:26:39.667 回答