How to create a TreeView with child nodes of diffe

2019-08-17 18:06发布

问题:

In my program I have a treeView for which I want to allow child nodes that are comboBoxes and textBlocks. My treeView along with it's nodes are created in an MVVM style. I know how to create textBlock child nodes, but have never created child nodes of any other UI tool.

My treeview's xaml:

TreeView ItemsSource="{Binding UserControl_DataModel.TreeViewViewModel.ObservableCollection<TreeViewDataModel>}" DisplayMemberPath="DisplayName.Value".../>

This is where new nodes are created and added to the TreeView (TreeViewViewModel):

private TreeViewDataModel createNewNode(string nodeName)
{
    var newNode = new TreeViewDataModel ()
    {
        DisplayName = nodeName
    };

    newNode.Children.Add(new TreeViewDataModel () { DisplayName = nodeName});

    return newNode;
}

public void addNewLocNode(string nodeName)
{
    TreeObservableCollection.Add(createNewNode(nodeName));
}

How do I create child nodes that are ComboBoxes, while still allowing the textblock children? This confuses me, because I don't see any part of the code that specifies what UI tool the children become. Please let me know if you need to see more code.

(Previous question about this same treeView if you need to reference it.)

Update:

Just for clarity, this is how my treeView nodes should look:

When I try something like this:

<HierarchicalDataTemplate DataType="{x:Type Data:Node}" ItemsSource="{Binding Teams}">
    <StackPanel>
        <TextBlock Text="{Binding IndividualProperty}" />
        <ComboBox ItemsSource="{Binding CollectionProperty}" />
    </StackPanel>
</HierarchicalDataTemplate>

I instead get this setup (it's like each item of the tree comes with a TextBlock and a ComboBox. Maybe there is another option besides StackPanel?):

Note that the comboBox is not a child of the textBlock node, but it's more like it's on the same level as the textBlock node.

回答1:

A ComboBox is a collection control. Therefore, you need a collection property in your 'node' object to bind to the ComboBox.ItemsSource. While an individual property in the 'node' object might need a HierarchicalDataTemplate somewhat like this:

<HierarchicalDataTemplate DataType="{x:Type Data:Node}" ItemsSource="{Binding Teams}">
    <TextBlock Text="{Binding IndividualProperty}" />
</HierarchicalDataTemplate>

You would need one more like this:

<HierarchicalDataTemplate DataType="{x:Type Data:Node}" ItemsSource="{Binding Teams}">
    <ComboBox ItemsSource="{Binding CollectionProperty}" />
</HierarchicalDataTemplate>

Or perhaps like this:

<HierarchicalDataTemplate DataType="{x:Type Data:Node}" ItemsSource="{Binding Teams}">
    <StackPanel>
        <TextBlock Text="{Binding IndividualProperty}" />
        <ComboBox ItemsSource="{Binding CollectionProperty}" />
    </StackPanel>
</HierarchicalDataTemplate>