List <string>不会更新回ListBox的ItemsSource?</string>

时间:2013-07-25 23:31:07

标签: c# wpf xaml

我是WPF的新手。我有一个List<string>作为ListBox's ItemsSource的来源。最初,ListBox会显示Items中的所有List<string>。但是,在尝试向我的List<string>添加一些字符串后,ListBox不会更新更改。我正在使用Binding将数据(后面)绑定到ListBox(视图),这是我的代码:

//Code behind
public MainWindow: Window {
   public MainWindow(){
      InitializeComponent();
      Items = new List<string>(){"1","2","3"};//after loaded, all these values are displayed OK in my ListBox.
      DataContext = this;
      //Try clicking on a button to add new value
      button1.Click += (s,e) => {
         Items.Add("4");//But my ListBox stays the same without any update/changes.
      };
   }
   public List<string> Items {get;set;}
}
//XAML
<ListBox ItemsSource={Binding Items}/>

请你指出我在这里做错了什么并给我一个解决方案?非常感谢你提前。

2 个答案:

答案 0 :(得分:3)

如果您已阅读documentation of ItemsSource,那么您就已经知道错误了。

  

[...]

     

此示例显示如何创建和绑定从ObservableCollection<T>类派生的集合,该集合类是在添加或删除项时提供通知的。

答案 1 :(得分:1)

你应该尝试使用ObservableCollection,因为它是 表示动态数据集合,在添加,删除项目或刷新整个列表时提供通知。

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Click="Button_Click" Content="Button" HorizontalAlignment="Left" Margin="441,289,0,0" VerticalAlignment="Top" Width="75"/>
        <ListBox HorizontalAlignment="Left" ItemsSource="{Binding MyList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Name="lstbox" Height="296" Margin="21,23,0,0" VerticalAlignment="Top" Width="209"/>

    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 WpfApplication3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<string> _myList = new ObservableCollection<string>(new List<string>(){"1","2","3"});
        int i = 3;  

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;  
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MyList.Add(i++.ToString());  
        }
        public ObservableCollection<string> MyList
        {
            get { return _myList; }
            set { _myList = value; }
        }
    }
}