我每次按下添加按钮时都会尝试在列表框中添加一个新项目,但由于某种原因它只添加了第一个,如果我再次按下它,它就不会添加第二个。
我现在看到的代码是如何创建一个名为_items的新列表,然后每次按下按钮时我都会在文本框中添加内容,然后我也会更新ItemSource。
每次按AddBtn时如何让它添加新项?
List<string> _items = new List<string>();
private void addBtn_Click(object sender, RoutedEventArgs e)
{
_items.Add(recipentTextbox.Text);
recipientLb.ItemsSource = _items;
}
答案 0 :(得分:2)
尝试使用ObservableCollection<string>
代替List<string>
。 ObservableCollection
支持数据绑定,并将更新目标属性。
答案 1 :(得分:0)
ObservableCollection<string> _items = new ObservableCollection<string>();
// Or whatever your constructor is
public MainWindow()
{
recipientLb.ItemsSource = _items;
}
private void addBtn_Click(object sender, RoutedEventArgs e)
{
_items.Add(recipentTextbox.Text);
}