2010-11-18 18 views
3

Je suis un débutant total dans WPF. Je voudrais lier les DataSet suivants contenant des nœuds et des relations à un TreeView. L'ensemble de données est:WPF comment lier un ensemble de données auto-référentiel à une arborescence

internal static DataSet getData() 
{ 
    DataTable dt = new DataTable("data"); 
    dt.Columns.Add("Id", typeof(int)); 
    dt.Columns.Add("ParentId", typeof(int)); 
    dt.Columns.Add("NodeDescription"); 

    dt.Rows.Add(1, null, "Employees"); 
    dt.Rows.Add(2, null, "Cars"); 
    dt.Rows.Add(3, 1, "Men"); 
    dt.Rows.Add(4, 1, "Women"); 
    dt.Rows.Add(5, 2, "BMW"); 
    dt.Rows.Add(6, 2, "Lexus"); 
    dt.Rows.Add(7, 3, "Adam Kowalski"); 
    dt.Rows.Add(8, 3, "Dawid Nowacki"); 
    dt.Rows.Add(9, 4, "Ilona Wacek"); 

    DataSet ds = new DataSet(); 
    ds.Tables.Add(dt); 

    //add a relationship 

    ds.Relations.Add("rsParentChild" 
    ,ds.Tables["data"].Columns["Id"] 
    ,ds.Tables["data"].Columns["ParentId"]); 

    return ds; 
} 

Je voudrais avoir:

alt text

Maintenant, j'en ce sens par resursive retrieveing ​​tous les nœuds DataTable et Ading au TreeView. Cependant, j'espère qu'il existe une liaison directe XAML.

Je voudrais ajouter que l'ensemble de données va changer dynamiquement et qu'il y a beaucoup de niveaux d'imbrication. Merci.

Répondre

5

Voici une solution simple qui fonctionne:

code-behind

public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
     var dataSet = getData(); 
     _rootNodes = dataSet.Tables["data"].DefaultView; 
     _rootNodes.RowFilter = "ParentId IS NULL"; 
     this.DataContext = this; 
    } 

    private DataView _rootNodes; 
    public DataView RootNodes 
    { 
     get { return _rootNodes; } 
    } 

    internal static DataSet getData() 
    { 
     ... 
    } 

} 

XAML

<TreeView ItemsSource="{Binding RootNodes}"> 
     <TreeView.ItemTemplate> 
      <HierarchicalDataTemplate ItemsSource="{Binding rsParentChild}"> 
       <TextBlock Text="{Binding NodeDescription}" /> 
      </HierarchicalDataTemplate> 
     </TreeView.ItemTemplate> 
    </TreeView> 
+0

brillant! Merci. – nan

+0

Qu'en est-il des tables de structure Entity? – ARZ

+0

Comment puis-je obtenir cela avec une liste d'objets en tant que DataSource? J'ai trouvé cette réponse: http://stackoverflow.com/questions/14161963/how-to-bind-self-referencing-table-to-wpf-treeview mais je suis incapable de comprendre le convertisseur mentionné ici. – Lorgarn