如何使用数据库WPF中的父/子创建动态TreeView

时间:2013-01-07 05:05:03

标签: c# wpf windows

我正在尝试使用以下代码创建动态Treeview。我正在使用用户控件

开启控制负载

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;
 }

使用此代码,我可以添加一个项目,但它没有正确添加。首先是在下面添加一个空节点,之后会添加项目。

我想要的是项目应该添加而不添加任何空节点,并且在单击父节点时,应该添加子节点。

如何将子节点添加到父节点?

2 个答案:

答案 0 :(得分:1)

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
}

答案 1 :(得分:0)

我发现在WPF中使用树视图非常具有挑战性。这篇文章非常有帮助:

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