WPF列表框 - 数据绑定问题

时间:2010-09-13 07:54:36

标签: c# wpf

我有这个问题,当我运行应用程序时,我看到列表框中的项目为“红色”,“蓝色”,“黄色”。但是当我输入“black”到textBox1并按下Button1项时没有添加。知道为什么吗?

 public partial class Window1 : Window
{
    private static ArrayList myItems = new ArrayList();
    public Window1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = myItems;
        myItems.Add("red");
        myItems.Add("blue");
        myItems.Add("yellow");   
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        myItems.Add(textBox1.Text);
    }
}

2 个答案:

答案 0 :(得分:3)

您应该使用ObservableCollection< string>替换ArrayList当内容发生变化时,它将与ListBox进行通信。

答案 1 :(得分:0)

这是因为视图(在这种情况下是列表框)没有被告知有关更改。

您应该实现INotifyProperyChanged或只是重置itemsSource:

private void button1_Click(object sender, RoutedEventArgs e)
{
    myItems.Add(textBox1.Text);
    // refresh:
    listBox1.ItemsSource = myItems;
}

(虽然使用OnPropertyChanged肯定是更好的做法。)