Search code examples
wpfdata-bindingtreeviewdataset

Binding TreeView to DataSet


I have a dataset I created from an Oracle Query. I get a datatable from a function and add it to dataset.

Now I try to bind to treeview to the ds. My code Behind:

private void init_TreeView()
        { 

           //TreeViewItem parent = PM_TreeView.Items.Add("Requirements");
           DataTable dt  =  DataBases.RunQuery();
           dt.TableName = "REQ";
           DataSet ds = new DataSet();
           ds.Tables.Add(dt);
           //ds.Relations.Add("rsParentChild", ds.Tables["REQ"].Columns["RQ_REQ_ID"], ds.Tables["REQ"].Columns["RQ_FATHER_ID"]);
           var dataSet = ds;
           _rootNodes = dataSet.Tables["REQ"].DefaultView;
           _rootNodes.RowFilter = "RQ_FATHER_ID = -1";
           this.DataContext = this;
         }

And

private DataView _rootNodes;

And

public DataView RootNodes
{
    get { return _rootNodes; }
}

And my XAML:

<TreeView x:Name="PM_TreeView" ItemsSource="{Binding RootNodes}" HorizontalAlignment="Left" Height="445" Margin="44.847,68.285,0,0" VerticalAlignment="Top" Width="320" Foreground="{x:Null}" BorderBrush="{x:Null}" Background="#FFBBB6B6" FontFamily="Segoe UI" FontSize="13.333">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding rsParentChild}">
                    <TextBlock Text="{Binding NodeDescription}" />
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

My datatable is:

RQ_REQ_ID RQ_FATHER_ID RQ_REQ_NAME
0         -1           REQ
1          0           QC11

But I get nothing on the treeview


Solution

  • I tried the following:

        <TreeView Name="tv" ItemsSource="{Binding Root}">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Parents}">
                    <TextBlock Text="{Binding Value}"/>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    

    and within my window i have:

            DataSet ds = new DataSet("Data");
    
            DataTable t = new DataTable("Table");
            t.PrimaryKey = new DataColumn[] { t.Columns.Add("Key", typeof(int)) };
            t.Columns.Add("Value", typeof(string));
            t.Columns.Add("Father", typeof(int));
            ds.Tables.Add(t);
    
            ds.Relations.Add("Parents", t.Columns["Key"], t.Columns["Father"], false);
    
            t.Rows.Add(1, "First", -1);
            t.Rows.Add(2, "Second", -1);
            t.Rows.Add(3, "Third", 2);
    
            Root = new DataView(t);
            Root.RowFilter = "[Father]<0";
            t.DefaultView.RowFilter = "[Father] < 0";
    
            tv.DataContext = this;
    

    where Root ist declared as:

    public DataView Root { get; private set; }
    

    The results are as expected.