我想使用以下模型在 TreeView 上创建数据绑定(bind):
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'
.为什么是这样?
最佳答案
你应该放弃 /
, DataContext
在 ItemTemplate
是一个项目,它本身没有当前项目。还有 Name
绑定(bind)不起作用,因为 DataContext
仍然是 Document
,您可以指定HierarchicalDataTemplate.ItemTemplate
,有DataContext
是 DocumentBlock
来自 Blocks
.
您通常使用 /
对于 TreeView 之外的详细信息 View ,例如<TextBlock Text="{Binding SourceDocuments/Blocks[0].Name}"/>
关于c# - 带数据绑定(bind)的 TreeView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434341/