我想将目录中的文件列表绑定到列表框。
这是我想尝试到目前为止的代码片段,lstFiles是一个ListBox,我想将Files属性绑定到。但ListBox是空的。请帮忙。
public partial class Form1 : Form, INotifyPropertyChanged
{
private IList<FileInfo> _files = new List<FileInfo>();
public IList<FileInfo> Files
{
get
{
return this._files;
}
set
{
if (value != this._files)
{
this._files = value;
NotifyPropertyChanged("Files");
}
}
}
public Form1()
{
InitializeComponent();
lstFiles.DataSource = Files;
lstFiles.DataBindings.Add("Name", Files, "Files");
lstFiles.DisplayMember = "Name";
}
private void btnStartPath_Click(object sender, EventArgs e)
{
var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
txtStartPath.Text = dialog.SelectedPath;
}
}
private void btnFind_Click(object sender, EventArgs e)
{
Files = new DirectoryInfo(txtStartPath.Text).EnumerateFiles().ToList();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
答案 0 :(得分:0)
我没有看到在代码中将文件添加到列表中
DirectoryInfo dinfo = new DirectoryInfo(@"C:\Directory");
文件类型,
_files = dinfo.GetFiles("*.txt");
然后
foreach( FileInfo file in Files )
{
listbox1.Items.Add(file.Name);
}
答案 1 :(得分:0)
您必须设置valuemember属性。我试过这个例子:
IList<FileInfo> myList = new List<FileInfo>();
FileInfo test1 = new FileInfo(@"G:\test.xls");
myList.Add(test1);
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "FullName";
listBox1.DataSource = myList;
这可以按预期工作:)