我綁定(至少我認爲我做到了)數據到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