Rocky
Rocky

Reputation: 4524

How to create Dynamic TreeView with Parent/Child from database WPF

I am trying to create a Dynamic Treeview with the following code. I am using User Control

On Control Load

TreeViewItem treeviewItems = new TreeViewItem();
treeviewItems.ItemsSource = TreeViewDataSource.DefaultView;
treeviewItems.ItemTemplate = GetHierarchicalData(ID, Desc);
treeViewCntrl.Items.Add(treeviewItems);

public HierarchicalDataTemplate GetHierarchicalData(string id, string desc)
{
   HierarchicalDataTemplate hierdatatemp = null;
   try
   {
    hierdatatemp = new HierarchicalDataTemplate(typeof(DataTable));
    hierdatatemp.ItemsSource = new Binding(itemSourceBindingName);
    FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
    textBlock.SetBinding(TextBlock.TextProperty, new Binding(desc));
    hierdatatemp.VisualTree = textBlock;
    }
    catch (Exception ex)
    {  }
    return hierdatatemp;
 }

With this code I am able to add an item but it is not adding properly. First it is adding an empty node under and the items are getting added after that.

What I want is items should add without adding any empty node, and on clicking on the Parent node, Child node should get added.

How to add a child node into parent node?

Upvotes: 0

Views: 5732

Answers (2)

Rocky
Rocky

Reputation: 4524

public TreeViewItem CreateTreeViewItem(string nodeName, string headerText, string ImagePath)
{
        TreeViewItem treeViewItem = new TreeViewItem();
        try
        {
            StackPanel stackPanel = new StackPanel();
            Label lblHeaderText = new Label();
            Image imgFrontIcon;
            imgFrontIcon = new Image(); 

            stackPanel.Orientation = Orientation.Horizontal;

            if (ImagePath != null && ImagePath != string.Empty)
            {
                Uri uri = new Uri(@"pack://application:,,," + ImagePath);
                BitmapImage bitMapSource = new BitmapImage();
                bitMapSource.BeginInit();
                bitMapSource.UriSource = uri;
                bitMapSource.EndInit();
                imgFrontIcon.Source = bitMapSource;
            }

            lblHeaderText.Content = headerText;
            stackPanel.Children.Add(imgFrontIcon);
            stackPanel.Children.Add(lblHeaderText);
            nodeName = nodeName.Replace("-", "_");
            treeViewItem.Name = nodeName;
            treeViewItem.Header = stackPanel;
        }
        catch (Exception ex)
        { }
        return treeViewItem
}

Upvotes: 1

Sebastian K
Sebastian K

Reputation: 6403

I found using a treeview in WPF quite challenging. This article was very helpful:

http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

Upvotes: 0

Related Questions