0
votes

I want to add an object from my viewmodel to a treeview, but I don't want to use a tree view item.

is there a way to do something like this?

<TreeView>
    <SomeTag Object="{Binding MyViewModel.MyObject}/>
</TreeView>

The problem is that I'm trying to bind to a non-homogenous data structure

ClassA
   ClassB
       ClassC (Collection)
          ClassD
          ClassD
          ...

I don't want a node for class A
Added a TreeViewItem for ClassB with static Header text.
Added a TreeViewItem for ClassC with static header text, bound ItemsSource to ClassC, and bound DisplayMemberPath set to a Name property.

Bind another control ro TreeView.SelectedItem. If I click a ClassB or ClassC item, the SelectedItem is a TreeViewItem. If I click a ClassD item, the SelectedItem is my object.

If trying to consistently get my object.

2
DId you add the viewmodel as datacontext of view?Subru
Yes. I can bind to my objects just fine. The problem is when I bind to TreeView.SelectedValue/Item I get the TreeViewItem, but if I use ItemsSource, the child nodes are the actual object.Matt M

2 Answers

0
votes

You can use the Tag Property.

<TreeView Tag="{Binding MyObject}" >
</TreeView>
0
votes

You can bind TreeViewItem's property like this:

<TreeView>
    <TreeView.Resources>
        <Style TargetType="TreeViewItem">
            <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource Ancestortype={x:Type TreeView}},Path=DataContext.anyobjectofViewmodel}"/>
        </Style>
    </TreeView.Resources>
............
............
</TreeView>