Praveen
Praveen

Reputation: 100

How bind an object to treeview from Xaml

I am trying to bind an object to the treeviewcontrol WPF by XAML, I am getting the treview as empty. When i am doing that by treeview.items.add(GetNode()) then its working.

I am using MVVM Framework(caliburn.Micro) I wanted to do it in Xaml, how do I assign Item source property in xaml? I tried with creating a property of Node class and calling the Method GetNode() with in the property, and assigned that property as itemssource of the treeview and changed the List to Observable collection. Still issue is same.

Working Xaml when doing treeview.items.Add(GetNode()) which returns a Node and and i as assigning Nodes collection to Hireachial Template.

<TreeView  Name="treeview2" 
            Grid.RowSpan="2"
            Grid.ColumnSpan="2"
            ItemContainerStyle="{StaticResource StretchTreeViewItemStyle}" Width="300">
            <TreeView.ItemTemplate>
                 <HierarchicalDataTemplate  ItemsSource="{Binding Nodes}">
                      <DockPanel LastChildFill="True">
                          <TextBlock  Padding="15,0,30,0" Text="{Binding Path=numitems}" TextAlignment="Right" 
    DockPanel.Dock="Right"/>
                          <TextBlock  Text="{Binding Path=Text}" DockPanel.Dock="Left" TextAlignment="Left" />
                      </DockPanel>
                 </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
  </TreeView>

Server Side Code:

this.treeview2.Items.Add(GetNode());

GetNode recursively build a list of type Node.

public class Node
{
    public string Text { get; set; }
    public List<Node> Nodes { get; set; }
    public ObservableCollection<Node> Nodes{get;set;} // with list and observable collection same results
    public int numitems { get; set; }
}

Upvotes: 0

Views: 1356

Answers (1)

Fede
Fede

Reputation: 44038

In addition to the HierarchicalDataTemplate, which seems just fine, add a binding to the ItemsSource property of your TreeView:

public class ViewModel
{
   private List<Node> _rootNodes;
   public List<Node> RootNodes 
   {
     get
     {
       return _rootNodes;
     }
     set
     {
       _rootNodes = value;
       NotifyPropertyChange(() => RootNodes);
     }
   }

   public ViewModel()
   {
      RootNodes = new List<Node>{new Node(){Text = "This is a Root Node}", 
                                 new Node(){Text = "This is the Second Root Node"}};
   }

And in XAML:

<TreeView ItemsSource="{Binding RootNodes}"
          .... />

Edit: Remove the call that does this.Treeview.... you don't need that. Try to keep to the minimum the amount of code that references UI Elements. You can do everything with bindings and have no need to manipulate UI Elements in code.

Upvotes: 1

Related Questions