这就是我让它工作的方式,谢谢马特!
public abstract class ObservableHierarchy<T>
{
public T Current { get; set; }
public ObservableCollection<ObservableHierarchy<T>> Children { get; set; }
public ObservableHierarchy( T current, Func<T, IEnumerable<T>> expand )
{
this.Current = current;
this.Children = new ObservableCollection<ObservableHierarchy<T>>();
foreach ( var item in expand( current ) )
{
Children.Add( Create( item ) );
}
}
protected abstract ObservableHierarchy<T> Create( T item );
}
然后我将该基类专门用于我当前使用的任何数据类。
public class ObservableFolderHierarchy:
ObservableHierarchy<FolderEntity>
{
public ObservableFolderHierarchy( FolderEntity root )
: base( root, x => x.FolderEntities )
{
}
protected override ObservableHierarchy<FolderEntity> Create( FolderEntity item )
{
return new ObservableFolderHierarchy( item );
}
}
稍微修改了 XAML,效果很好!对 Current 的集合或属性的更改会相应地更新 TreeView。
<HierarchicalDataTemplate DataType="{x:Type ui:ObservableFolderHierarchy}"
ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<Image Source="/UI/Resources/folder.png" Width="16" Height="16"/>
<TextBlock Text="{Binding Current.FolderName}"/>
</StackPanel>
</HierarchicalDataTemplate>