如何从数据库 WPF 创建带有父/子的动态 TreeView [英] How to create Dynamic TreeView with Parent/Child from database WPF

查看:30
本文介绍了如何从数据库 WPF 创建带有父/子的动态 TreeView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码创建动态树视图.我正在使用用户控制

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

控制负载

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?

推荐答案

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
}

这篇关于如何从数据库 WPF 创建带有父/子的动态 TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆