I bound (at least i think i did) data to a ListBox following a tutorial. The class element I want bound has data in it but i see nothing on the ListBox after some event. I have the following partial XAML:
<ListBox x:Name="jukeBoxListBox" Height="227" VerticalAlignment="Top" ItemsSource="{Binding FilePathList}"/>
In the WPF form cs file I have. Should i set to class FolderItems or its attr filePathList? Also should I use ObservableCollection instead of list?
InitializeComponent();
FolderItems folderItems = new FolderItems();
this.DataContext = folderItems.FilePathList;
My data class:
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");
}
}
}
}
I think I need to mention that I change the List elements in a Button click event. Maybe the below is a part of the problem.
//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);
}
I hail from Javaland and am brand new to C#. Please excuse my language.
If you’d change
List<string>toObservableCollection<string>(see here), your binding would get notified about changes in the list, e.g. when you add items.Also, you must change the property name in the Notify call to
filePathList.And you should follow coding conventions for properties in .Net, which are usually written with a leading uppercase character. So your property would be
FilePathList.Change the binding to the renamed property:
See also Binding to Collections and Using Collection Objects as a Binding Source.
UPDATE
Your
ProcessFilesmethod should be written as shown below to enable recursion.And be called like this:
Or if you need to access the
FolderItemsobject later (perhaps in some event handler) you might get it back from theDataContext: