使用动态上下文菜单C#WPF创建自定义树视图

时间:2014-03-09 21:11:05

标签: c# .net wpf tree treeview

我想从C#WPF中的列表创建动态树视图。所以我将从列表中获取所有队列(queue1,...)和主题(topic1,...)。此外,我需要一个特定的上下文菜单,用于不同的分层点。我想创建一个这样的树视图:

队列

  • 队列1
  • 队列2

主题

  • TOPIC1
  • 标题2

应该有主要点队列的特定上下文菜单和主要点主题的特定上下文菜单。另外我需要一个特定的子项queues1和topic1。我试了几件但没有成功。有没有人举一个小例子来说明解决这个问题的人?

最好的问候

2 个答案:

答案 0 :(得分:1)

创建树不是问题。它涉及一些工作,但直接。您必须从列表中创建分层数据模板并填充树。以下链接包含所有信息。

Creating a wpf tree

如果您不想使用sdk

页面资源:     

xaml中的

树:

<Grid TextElement.FontSize="10" DataContext="{StaticResource MyHierarchicalViewSource}" >
<GroupBox x:Name="gbTree">
<TreeView Name="HierarchyTreeview" HorizontalAlignment="Left" AllowDrop="True"
          BorderThickness="0" VerticalAlignment="Top" Height="Auto" 
                              ItemsSource="{Binding}">
 <TreeView.ItemTemplate>
   <HierarchicalDataTemplate ItemsSource="{Binding Itemchildren, Mode=TwoWay}">
      <StackPanel Orientation="Horizontal" Margin="2">

        <TextBlock x:Name="text" Text="{Binding Item.ItemLabel}" >
        </TextBlock>

     </StackPanel>
     </HierarchicalDataTemplate>
   </TreeView.ItemTemplate>
  </TreeView> 
 </GroupBox>
</Grid>

代码behing:

    Me._HierarchyViewSource = CType(Me.Resources("MyHierarchicalViewSource"), System.Windows.Data.CollectionViewSource)
Me._HierarchyViewSource.Source = your hierarchical data collection

假设您的层次结构类结构:

Item has
 ItemChildren collection

但是,我在创建特定的上下文菜单时遇到了同样的问题。我发布了自己的问题,还没有找到解决方案。我试图用数据触发器做到这一点没有运气。我知道的唯一方法是为整个树创建一个上下文菜单,并根据项目类型使其可见或不可见。

如果我找到解决方法,我会发布。

答案 1 :(得分:0)

我使用以下代码将其动态添加到TreeView。

CategorieList-具有ID,名称,布尔值作为父类别的IsSubCategory和Id的类别的集合。

private void AddToTree()
        {
            List<Category> topCategory = CategorieList.Where(c => c.IsSubCategory == false).ToList();

            foreach(Category c in topCategory)
            {
                CategoryTree.Items.Add(CreateTreeViewItem(c));
            }
        }

    private TreeViewItem CreateTreeViewItem(Category category)
    {
        TreeViewItem tItem = new TreeViewItem();
        tItem.Header = category.Name;
        List<Category> sub = CategorieList.Where(c => category.Id == c.ParentCategory).ToList();
        if (null != sub && sub.Count() != 0)
        {
            foreach (Category c in sub)
            {
                TreeViewItem item = CreateTreeViewItem(c);
                tItem.Items.Add(item);
            }
        }

        return tItem;
    }

XAML代码在下面

<TreeView x:Name="CategoryTree"> </TreeView>