我绑定(至少我认为我做到了)数据到ListBox
后面的教程。我想绑定的类元素中包含数据,但在某些事件发生后,我在ListBox
上看不到任何内容。我有以下部分XAML:listbox绑定不起作用,因为它应该
<ListBox x:Name="jukeBoxListBox" Height="227" VerticalAlignment="Top" ItemsSource="{Binding FilePathList}"/>
我在WPF窗体cs文件中。我应该设置为课程FolderItems
还是其attr filePathList
?我也应该使用ObservableCollection
而不是list
?
InitializeComponent();
FolderItems folderItems = new FolderItems();
this.DataContext = folderItems.FilePathList;
我的数据类:
class FolderItems : INotifyPropertyChanged
{
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion INotifyPropertyChanged implementation
private ObservableCollection<String> _pathList = new ObservableCollection<string>();
public ObservableCollection<String> FilePathList
{
get { return _pathList; }
set
{
if (value != _pathList)
{
_pathList = value;
Notify("FilePathList");
}
}
}
}
我想我需要一提的是我改变一个Button
click事件的List
元素。也许下面是问题的一部分。
//in the event fItems is an instance of FolderItems
var files = new ObservableCollection<string>();
ProcessFiles(of.SelectedPath, files);
fItems.FilePathList = files;
//...
private void ProcessFiles(string path, ICollection<string> files)
{
foreach (var file in Directory.GetFiles(path).Where(name => name.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)))
files.Add(file);
foreach (var directory in Directory.GetDirectories(path))
ProcessFiles(directory, files);
}
我来自Javaland,是全新的C#。请原谅我的语言。
您在循环目录时忽略了调用'ProcessFiles'返回的集合。您应该将集合作为方法参数传递给'ProcessFiles',并将文件名添加到始终相同的集合中。 – Clemens