我正在尝试将项目添加到 ComboBox
(比如 Name="labelComboBox"
)在运行时当我按下添加按钮时(比如 Name="add2labels" Click="add2labels_Click"
)。但是 ComboBox
无法显示我新添加的值。我错过了什么?
以下是添加按钮的事件处理程序:
private List<String> labels = new List<String>();
... ...
private void add2labels_Click(object sender, RoutedEventArgs e)
{
labels.Add("new value");
labelComboBox.ItemsSource = labels;
}
附言我很确定这些值已添加到 List<String> labels
正确(它的计数每次都增加)。
更新了可行的解决方案(3 种方式):
使用
ObservableCollection
(@AnatoliyNikolaev 的回答)。更改
List<String> labels
至ObservableCollection<String> labels
.并且只需要调用labelComboBox.ItemsSource = labels;
一次。使用
Binding
(@HarshanaNarangoda 的回答)。添加
ItemsSource="{Binding Path=labels}"
至ComboBox
的属性。使用
Refresh()
(@EliranPe'er 的回答)。将事件处理程序更改为:
... ... labelComboBox.ItemsSource = labels; labelComboBox.Items.Refresh(); // new added
最佳答案
你应该使用 ObservableCollection<T>
而不是 List<String>
:
ObservableCollection represents a dynamic data collection that
provides notifications
when items get added, removed, or when the whole list is refreshed.
关于c# - 在运行时向 ComboBox 添加项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21900332/