我正在尝试将类对象绑定到WPF应用程序。但它每次都会抛出方法中的异常。在下面的代码中发生异常的注释。有什么建议吗?
namespace Explorer
{
class DirectoryTree : INotifyPropertyChanged
{
//members
private string _path;
private string _name;
private ObservableCollection<DirectoryTree> _SubDirectories;
//private ObservableCollection<FileInfo> _files;
//properties
public string Path
{
get { return _path; }
set
{
if(_path != value)
{
_path = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Path"));
}
}
}
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
public ObservableCollection<DirectoryTree> SubDirectories
{
get { return _SubDirectories; }
set
{
if (_SubDirectories != value)
{
_SubDirectories = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SubDirectories"));
}
}
}
//method to process the directory recursively
public DirectoryTree TraverseDirectory(DirectoryInfo rootdirectory)
{
DirectoryTree directoryTree = new DirectoryTree();
directoryTree.Path = rootdirectory.FullName;
directoryTree.Name = directoryTree.Path.Substring(directoryTree.Path.LastIndexOf("\\") + 1);
if(directoryTree !=null)
{
//process all the files under this directory
List<FileInfo> files = new List<FileInfo>(rootdirectory.GetFiles("*.*").ToList());
if (files.Count > 0)
{
foreach (FileInfo f in files)
{
try
{
DirectoryTree fileInTree = new DirectoryTree();
fileInTree.Path = f.Directory.ToString();
fileInTree.Name = f.Name;
directoryTree.SubDirectories.Add(fileInTree);//object reference not set to an instance of an object
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//process all the directories under the current directory
List<DirectoryInfo> directories = new List<DirectoryInfo>(rootdirectory.GetDirectories().ToList());
if (directories.Count > 0)
{
foreach (DirectoryInfo d in directories)
{
DirectoryTree directoryInTree = new DirectoryTree();
directoryInTree.Path = d.FullName;
directoryInTree.Name = d.Name;
directoryTree.SubDirectories.Add(directoryInTree);
TraverseDirectory(d);
}
}
}
return directoryTree;
}
public event PropertyChangedEventHandler PropertyChanged;
}
}