c# - 在运行时向 ComboBox 添加项目?

标签 c# wpf xaml combobox

我正在尝试将项目添加到 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 种方式):

  1. 使用 ObservableCollection (@AnatoliyNikolaev 的回答)。

    更改 List<String> labelsObservableCollection<String> labels .并且只需要调用labelComboBox.ItemsSource = labels;一次。

  2. 使用 Binding (@HarshanaNarangoda 的回答)。

    添加ItemsSource="{Binding Path=labels}"ComboBox的属性。

  3. 使用 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/

相关文章:

WPF 删除菜单项和 ListView 上的鼠标悬停/悬停边框

xaml - Metro 风格 : Scrolling with mouse wheel

c# - GetCursorInfo WinForms 与 WPF C#

c# - C# 和 VB.Net 自定义类之间的区别

c# - 在 WPF 应用程序的属性中设置/返回值

wpf - 如何使 WPF ListView 项目水平和垂直重复?

c# - WP7 - 文本框光标位置错误

c# - 我可以将 UseCSharpNullComparisonBehavior 用于单个查询吗?

c# - 在 SslStream 中禁用不安全的重新协商

.net - 如何将图像 MouseDown 事件与 RoutedUICommand 绑定(bind)