绑定DataGrid不更新集合更改

时间:2011-11-04 01:56:45

标签: c# wpf bind

我是WPF的菜鸟。希望我能找到答案。

例如, 我有一个List<Customer>,它绑定到dataGrid。如果我将新客户添加到列表中,并且我没有看到datagrid在那里添加新行。

<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" Height="318">
    <DataGrid.Columns>
        <DataGridTextColumn Header="First Name" Binding="{Binding FirstName, Mode=TwoWay}" />
        <DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Height="80" Source="{Binding Image,Mode=TwoWay}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Data;

namespace DataGrid
{
    public class MainWindowViewModel
    {
        public ICollectionView Customers { get; private set; }
        public ICollectionView GroupedCustomers { get; private set; }
        public List<Customer> _customers { get; set; }

        public MainWindowViewModel()
        {
            _customers = new List<Customer>
                             {
                                 new Customer
                                     {
                                         FirstName = "Christian",
                                         LastName = "Moser",
                                         Gender = Gender.Male,
                                         WebSite = new Uri("http://www.wpftutorial.net"),
                                         ReceiveNewsletter = true,
                                         Image = "Images/christian.jpg"
                                     },
                                 new Customer
                                     {
                                         FirstName = "Peter",
                                         LastName = "Meyer",
                                         Gender = Gender.Male,
                                         WebSite = new Uri("http://www.petermeyer.com"),
                                         Image = "Images/peter.jpg"
                                     },
                                 new Customer
                                     {
                                         FirstName = "Lisa",
                                         LastName = "Simpson",
                                         Gender = Gender.Female,
                                         WebSite = new Uri("http://www.thesimpsons.com"),
                                         Image = "Images/lisa.jpg"
                                     },
                                 new Customer
                                     {
                                         FirstName = "Betty",
                                         LastName = "Bossy",
                                         Gender = Gender.Female,
                                         WebSite = new Uri("http://www.bettybossy.ch"),
                                         Image = "Images/betty.jpg"
                                     }
                             };
            Customers = CollectionViewSource.GetDefaultView(_customers);
            GroupedCustomers = new ListCollectionView(_customers);
            GroupedCustomers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));         
        }
    }
}

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;
using System.Reflection;

namespace DataGrid
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private new MainWindowViewModel view { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            view = new MainWindowViewModel();
            DataContext = view;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            view._customers.Add(new Customer
                                {
                                    FirstName = "Lei",
                                    LastName = "Moser",
                                    Gender = Gender.Male,
                                    WebSite = new Uri("http://www.wpftutorial.net"),
                                    ReceiveNewsletter = true,
                                    Image = "Images/christian.jpg"
                                });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace DataGrid
{    
    public enum Gender
    {
        Male, 
        Female
    }

    public class Customer : INotifyPropertyChanged
    {
        private string _firstName;
        private string _lastName;
        private Gender _gender;
        private Uri _webSite;
        private bool _newsletter;
        private string _image;

        public string FirstName
        {
            get { return _firstName; }
            set 
            {
                _firstName = value;
                NotifyPropertyChanged("FirstName");
            }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                _lastName = value;
                NotifyPropertyChanged("LastName");
            }
        }

        public Gender Gender
        {
            get { return _gender; }
            set
            {
                _gender = value;
                NotifyPropertyChanged("Gender");
            }
        }

        public Uri WebSite
        {
            get { return _webSite; }
            set
            {
                _webSite = value;
                NotifyPropertyChanged("WebSite");
            }
        }

        public bool ReceiveNewsletter
        {
            get { return _newsletter; }
            set
            {
                _newsletter = value;
                NotifyPropertyChanged("Newsletter");
            }
        }

        public string Image
        {
            get { return _image; }
            set
            {
                _image = value;
                NotifyPropertyChanged("Image");
            }
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        #region Private Helpers
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}

我将bindingMode设置为TwoWay,我有一个button_onClick,只是将新客户添加到绑定列表中,但我没有看到Datagrid为它添加新行。
有人可以帮忙吗?

2 个答案:

答案 0 :(得分:5)

问题是List<T>没有实现INotifyCollectionChanged。没有它,没有任何东西告诉WPF已经添加了一个新项目。

此处最好的选择是将您的班级更改为使用ObservableCollection<T>而不是List<T>。这将导致WPF在集合中添加或删除项目时自动得到通知,并且会相应地更新。

答案 1 :(得分:0)

您的List对象可能不会继承INotiftyPropertyChanged,因此它不会告诉您的程序更新对象。

如果您可以发布一些代码,我们可以确定是否是这种情况或导致问题的原因。