List 不会更新回 ListBox 的 ItemsSource

本文关键字:ListBox ItemsSource 更新 string List | 更新日期: 2023-09-27 18:25:03

我是WPF的新手。我有一个List<string>作为我ListBox's ItemsSource的来源。最初,ListBox显示我List<string>中的所有Items正常。但是,在尝试向我的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}/>

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

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

如果你读过ItemsSource的文档,你就会知道出了什么问题。

[...]

此示例演示如何创建并绑定到派生自 ObservableCollection<T> 类的集合, 类是一个集合类,可在添加或删除项时提供通知。

你应该尝试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; }
        }
    }
}