0

我是 WPF 的新手。我有一个List<string>作为我的ListBox's ItemsSource. 最初,ListBox显示一切都Items在我的List<string>OK 中。但是,在尝试向 my 添加一些字符串后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}/>

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

4

2 回答 2

3

如果您阅读过文档,ItemsSource您已经知道出了什么问题。

[...]

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

于 2013-07-25T23:33:33.597 回答
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; }
        }
    }
}
于 2013-07-25T23:56:36.800 回答