2013-01-07 74 views
0

我想用下面的代碼創建一個動態樹形視圖。我使用的用戶控制如何使用父/子從數據庫WPF創建動態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; 
} 

有了這個代碼,我可以添加一個項目,但不加入正常。首先,它將在下面添加一個空節點,並在此之後添加項目。

我想要的是項目應該添加而不添加任何空節點,並且在單擊父節點時應該添加子節點。

如何將子節點添加到父節點中?

+0

有人請幫助我.. – Rocky

回答

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 
} 
相關問題