繁体   English   中英

绑定列表<string>到 combobox</string>

[英]Bind a List<string> to a combobox

我有一个字符串列表。 我想用字符串列表填充组合框。 我该怎么做呢? 我所有的尝试和搜索都是死路一条。

我用了:

<ComboBox  Name="comboBox2" ItemsSource="{Binding Combobox2items}" />
 public partial class EditRule : Window
{
    public ObservableCollection<string> Combobox2items { get;  set; }

    public EditRule()
    {
        InitializeComponent();
        Combobox2items = new ObservableCollection<string>();
    Combobox2items.Add("DFd");

    }}

编辑:添加Combobox2items.ItemsSource = Combobox2items; 有效,但为什么 ItemsSource="{Binding Combobox2items}" 没有?

您可以通过 2 种方式填充 ComboBox,实际上是每个 ItemsControl。

第一:直接向其中添加项目,在代码或 Xaml 中工作

<ComboBox>
    <ComboBoxItem Name="Item1" />
    <ComboBoxItem Name="Item2" />
</ComboBox>

但这是相当 static。 第二种方法使用动态列表。

例如,假设您的 xaml 中有一个 window 和一个 combobox。 Combobox 得到x:Name="myCombobox"

在您后面的代码中,您可以创建您的列表并将其设置为ItemsSource

List<string> myItemsCollection = new List<string>();
public Window1()
{
   InitializeComponent();
   myItemsCollection.Add("Item1");
   myCombobox.ItemsSource = myItemsCollection;
}

这工作正常,但有一个问题。 如果在将 List 设置为 ItemsSource 后更改了 List,UI 将无法赶上最新的更改。 因此,为了使其也能正常工作,您需要使用ObservableCollection现在该集合可以通知 UI 将侦听的任何更改。 并自动将新项目添加到 combobox。

WPF 中的任何基于列表的控件都有一个ItemsSource属性,您可以将列表分配或绑定到该属性。 在代码中:

comboBox1.ItemsSource = myList;

...或者如果您的列表是 object 上的属性,这是您的 Window 的 DataContext:

<ComboBox ItemsSource="{Binding MyList}" />

使用ObservableCollection<string>而不是List<string> ,它为您实现INotifyCollectionChanged

ObservableCollection Class

WPF 提供 ObservableCollection class,它是实现 INotifyCollectionChanged 接口的数据集合的内置实现

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM