首页 > 解决方案 > 动态创建 ComboBox 项,用数据填充它们并命名它们?

问题描述

我想检测目录中有多少文件,然后使用该数字将相同数量的项目添加到 ComboBox。但是当我创建项目时,如何给每个项目一个单独的名称?“添加”只为项目提供其内容,但我想给它一个 x:Name。这是我到目前为止所拥有的:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    if (!File.Exists(@"C:\_Kooper Young FBLA\CIC=true.txt"))
    {
        int FileAmount = Directory.GetFiles(@"C:\_Kooper Young FBLA").Length;

        for (int i = 1; i < FileAmount + 1; i++)
        {
            ComboBox.Items.Add();
        }
    }

    File.Create(@"C:\_Kooper Young FBLA\CIC=true.txt");
}

标签: c#wpf

解决方案


正如您在 WPF 中一样,我最好建议您将其Binding用于您的 ComboBox。

这是一个简单的方法,创建一个类 ComboItem :

public class ComboItem
{
    public string FileName { get; set; }    
}

因此,在您的代码中,您只需要执行以下操作:

public ObservableCollection<ComboItem> ComboFiles { get; }
    = new ObservableCollection<ComboItem>();

foreach (var file in Directory.GetFiles(directoryName)) 
{
    ComboFiles.Add(new ComboItem { FileName = file });
}

这样您就可以填充您的 ComboBox 列表。然后在您的 xaml 中,您可以像这样绑定到您的 ObservableCollection:

<ComboBox Grid.Column="1" ItemsSource="{Binding Path=ComboFiles}" 
    SelectedItem="{Binding Path=SelectedFile}" DisplayMemberPath="FileName"/>

SelectedFile 是一个ComboItem对象。

当然答案不是“钥匙在手”,而是对Binding做一些研究我相信你会很快找到它,我只能告诉你那个链接


推荐阅读