2012-07-11 93 views
0

我想在與下面的模型一個TreeView創建數據綁定: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

錯誤在這裏[http://stackoverflow.com/questions/1138471/binding-to-the-current-item-wpf]與你所看到的有關嗎? – AksharRoop 2012-07-11 14:03:42

回答

4

您應該刪除/,DataContext中的ItemTemplate是一個項目,它沒有當前項目本身。由於DataContext仍然是Document,所以Name綁定將不起作用,您可以指定HierarchicalDataTemplate.ItemTemplate,那麼DataContextBlocks中的DocumentBlock

您通常使用/獲取詳細視圖以外的TreeView,例如, <TextBlock Text="{Binding SourceDocuments/Blocks[0].Name}"/>