用文本文件填充列表框

filling listbox with textfile

因此,我试图用我已放入 txt 文件中的名称填充列表框。 当我使用 Console.WriteLine(naam) 时,它实际上显示了文件中的名称,但我无法将它们放入列表框中。有谁知道这个问题的解决方案?感谢冒险。

public void PopulateList( ListBox list, string file)
{
        string naam;
        string sourcepath =  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
        string myfile = System.IO.Path.Combine(sourcepath, file);
        StreamReader reader = File.OpenText(myfile);
        naam = reader.ReadLine();
        while (naam != null)
        {
            list.Items.Add(naam);
            list.Items.Add(Environment.NewLine);
            naam = reader.ReadLine();
        }
        reader.Close();
}

看看this

StreamReader sr = new StreamReader("youfilePath");
string line = string.Empty;
try
{
    //Read the first line of text
    line = sr.ReadLine();
    //Continue to read until you reach end of file
    while (line != null)
    {
        list.Items.Add(line);
        //Read the next line
        line = sr.ReadLine();
    }

    //close the file
    sr.Close();
}
catch (Exception e)
{
    MessageBox.Show(e.Message.ToString());
}
finally
{
    //close the file
    sr.Close();
}

您可以使用 File.ReadLines 使它变得更好:

string sourcepath =  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
string myfile = Path.Combine(sourcepath, file);

var items = File.ReadAllLines(myfile)
    .Select(line => new ListItem(line));

List.Items.AddRange(items);

首先请使用 MVVM 开发任何 wpf 应用程序。像这样在代码隐藏中操作 UI 控件是不好的。使用正确的绑定。

如果我必须解决这个问题,我会创建像

这样的字符串集合
 public ObservableCollection<string> Names { get; set; }

并像

一样将它绑定到 ListBox
 <ListBox x:Name="NamesListBox" ItemsSource="{Binding Names}"/>

然后在我的 Window 的构造函数中,我将初始化 Names 并设置 Window 的 DataContext 并更新 PopulateList 方法,如下所示:

    public MainWindow()
    {
        InitializeComponent();
        Names = new ObservableCollection<string>();
        DataContext = this;
        PopulateList("C:\names.txt");
    }

    public void PopulateList(string file)
    {
        string naam;
        string sourcepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string myfile = System.IO.Path.Combine(sourcepath, file);
        StreamReader reader = File.OpenText(myfile);
        naam = reader.ReadLine();
        while (naam != null)
        {
            Names.Add(naam);
            naam = reader.ReadLine();
        }
        reader.Close();
    }