附加到全球列表

时间:2016-04-22 04:35:50

标签: c# .net wpf

我刚开始学习WPF和C#。我有一个全局列表,我想在活动中附加。

代码:

public partial class MainWindow : Window
{
    public List<User> items = new List<User>();

    someEventHandler
           {
                items.Add(new User() { Name = "John", Age = 42 });
                listViewUsers.ItemsSource = items;
           }
}

但是,这仅在事件第一次触发时更新,而不是后续事件。如果我搬家

public List<User> items = new List<User>();

到someEventHandler,listViewUsers将只显示最新的更新而不是之前的记录。如何追加物品?

2 个答案:

答案 0 :(得分:3)

虽然我更喜欢通过ViewModel绑定xaml中的所有内容,但为了解决您的问题,您应该使用ObservableCollection,如下所示。如果在集合中添加了项目,它将自动更新列表视图:

    public partial class MainWindow : Window
    {
        public ObservableCollection<User> items = new ObservableCollection<User>();

        public MainWindow()
        {
            InitializeComponent();
            listViewUsers.ItemsSource = items;

        }

         someEventHandler
           {
                items.Add(new User() { Name = "John", Age = 42 });

           }
}

答案 1 :(得分:1)

尝试使用ObservableCollectionObservableCollection是一个通用动态数据集合,可在添加,删除项目或刷新整个集合时提供通知。

public partial class MainWindow : Window
{
    public ObservableCollection<User> items = new ObservableCollection<User>();

    someEventHandler
    {
         items.Add(new User() { Name = "John", Age = 42 });

    }
}

其他选项是明确实施INotifyPropertyChanged 并通知变更。

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private List<User> items;
    public List<User> Items 
    {
         get {return items; }
         set {items=value;  onPropertyChanged(this, "Items") }; 
    }

    someEventHandler
    {
         items.Add(new User() { Name = "John", Age = 42 });
         onPropertyChanged(this, "Items") 
    }



    // Declare the PropertyChanged event
    public event PropertyChangedEventHandler PropertyChanged;

    // OnPropertyChanged will raise the PropertyChanged event passing the
    // source property that is being updated.
    private void onPropertyChanged(object sender, string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
        }
    }