gpt4 book ai didi

c# - 带数据绑定(bind)的 TreeView

转载 作者:行者123 更新时间:2023-12-03 10:55:34 26 4
gpt4 key购买 nike

我想使用以下模型在 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' .为什么是这样?

最佳答案

你应该放弃 / , DataContextItemTemplate是一个项目,它本身没有当前项目。还有 Name绑定(bind)不起作用,因为 DataContext仍然是 Document ,您可以指定HierarchicalDataTemplate.ItemTemplate ,有DataContextDocumentBlock来自 Blocks .

您通常使用 /对于 TreeView 之外的详细信息 View ,例如<TextBlock Text="{Binding SourceDocuments/Blocks[0].Name}"/>

关于c# - 带数据绑定(bind)的 TreeView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com