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

标签 c# wpf data-binding mvvm

我想使用以下模型在 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/

相关文章:

c# - 从 Azure Ping 客户端 LAN

c# - C#中的ARIMA算法

c# - 具有 OneWayToSource 绑定(bind)的 SelectedIndex 不会触发

java - Android数据绑定(bind)问题绑定(bind)适配器调用两次

c# - 从 Matlab 到 C#

c# - 如何在 C# 中监视 SQL Server 代理作业信息

WPF:如何以原始尺寸显示图像?

wpf - 来自文件 PixelFormat 的 BitmapImage 始终是 bgr32

.net - 如何在XAML中实现圆形按钮

java - Android 布局文件中的数据绑定(bind)错误