我想在TreeView上使用以下模型创建数据绑定:
public partial class MainWindow : Window
{
private ViewModel model = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = model;
}
...
}
public class ViewModel : ObservableObject
{
private IList<Document> sourceDocuments;
public IList<Document> SourceDocuments
{
get { return sourceDocuments; }
set
{
sourceDocuments = value;
OnPropertyChanged("SourceDocuments");
}
}
public ViewModel()
{
SourceDocuments = new ObservableCollection<Document>();
}
}
public class Document
{
public String Filename;
public IList<DocumentBlock> Blocks { get; set; }
public Document(String filename)
{
this.Filename = filename;
Blocks = new List<DocumentBlock>();
}
}
public class DocumentBlock
{
public String Name { get; private set; }
public DocumentBlock(String name)
{
this.Name = name;
}
public override string ToString()
{
return Name;
}
}
这个XAML
<TreeView HorizontalAlignment="Left" Margin="6,6,0,6" Name="SourceDocumentsList" Width="202"
ItemsSource="{Binding SourceDocuments}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding /Blocks}">
<TextBlock Text="{Binding /Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
我收到错误消息'Blocks' property not found on 'current item of collection' ''Document'
。这是为什么?
答案 0 :(得分:4)
您应该放弃/
,DataContext
中的ItemTemplate
是一个项目,它本身没有当前项目。 Name
绑定也不起作用,因为DataContext
仍然是Document
,您可以指定HierarchicalDataTemplate.ItemTemplate
,DataContext
是DocumentBlock
1}}来自Blocks
。
您通常使用/
获取TreeView 之外的详细信息视图,例如<TextBlock Text="{Binding SourceDocuments/Blocks[0].Name}"/>