I have the following two model-classes:
public class FileItem : NotifyBase
{
public FileItem(string fullPath)
{
FullPath = fullPath;
}
public string FullPath
{
get { return Get<string>(); }
set
{
Set(value);
OnPropertyChanged("FileName");
OnPropertyChanged("Directory");
}
}
public string Directory
{
get { return Path.GetDirectoryName(FullPath); }
}
public string FileName
{
get { return Path.GetFileName(FullPath); }
}
}
and
public class Directory : NotifyBase
{
public Directory(string fullPath)
{
FullPath = fullPath;
Files = new ObservableCollection<FileItem>();
Directories = new ObservableCollection<Directory>();
}
public ObservableCollection<FileItem> Files
{
get { return Get<ObservableCollection<FileItem>>(); }
set { Set(value); }
}
public ObservableCollection<Directory> Directories
{
get { return Get<ObservableCollection<Directory>>(); }
set { Set(value); }
}
public string FullPath
{
get { return Get<string>(); }
set
{
Set(value);
OnPropertyChanged("DirectoryName");
}
}
public string DirectoryName
{
get
{
string[] directoryNameSplit = FullPath.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
if (directoryNameSplit.Length > 0)
{
return directoryNameSplit[directoryNameSplit.Length - 1];
}
return "UNKNOWN";
}
}
}
The class NotifyBase
is just an implementation of INotifyPropertyChanged
.
I load the data from the filesystem and so I have a hierarchy of objects. Now I want to display that hierarchy of Directory
s and FileItem
s in the View as a TreeView
.
In the ViewModel I have an ObservableCollection<Directory>
called Directories with the root nodes.
My View is:
<TreeView Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Margin="5" x:Name="tv"
ItemsSource="{Binding Directories, UpdateSourceTrigger=PropertyChanged}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type model:Directory}" ItemsSource="{Binding Directories}">
<Label Content="{Binding Path=DirectoryName}" VerticalAlignment="Center"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type model:FileItem}">
<Label Content="{Binding FileName}" VerticalAlignment="Center" Background="Red"/>
</DataTemplate>
</TreeView.Resources>
</TreeView>
All folders are displayed perfect, but I don't see any FileItem
s and I don't know why. What I'm doing wrong here?
答案 0 :(得分:0)
Because you have your two collections separate, and you are not binding to Files
anywhere.
Instead of two collections, have one collection of two types.