3

Consider the following data structure:

List<Person> People;
class Person { 
  List<Car> Cars; 
  List<Hobby> Hobbies;
}

I want to bind a TreeView to this structure. And it should look like this:

People
> Frank
  > Cars
    > BMW
    > Ford
  > Hobbies
    > Tennis
    > Golf
> Jane
  > Cars
  > Hobbies

How can this be achieved in XAML? Here's what I've got so far:

<TreeView>
  <TreeView.Resources>
    <DataTemplate x:Key="PersonTemplate">
      <TextBlock Header="{Binding Name}">
        <TextBlock.ContextMenu>
          <ContextMenu>
            <MenuItem Header="Remove" />
          </ContextMenu>
        </TextBlock.ContextMenu>
      </TextBlock>
    </DataTemplate>
  </TreeView.Resources>

  <TreeViewItem Header="{Binding Name}"IsExpanded="True" >
    <TreeViewItem Header="People" 
             ItemsSource="{Binding People}"
            ItemTemplate="{StaticResource PersonTemplate}">
    </TreeViewItem>
  </TreeViewItem>
</TreeView>

This is a follow up question to binding-a-treeview-with-contextmenu-in-xaml

1 Answer 1

5

This is a great way to get started using MVVM for treeview binding:

http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx

Sign up to request clarification or add additional context in comments.

3 Comments

You beat me to it :-) This is such a clean abstraction of presentation and data(Model)-layer. I've actually used Josh's example in production code and it works beautifully.
I agree, working through this specific sample really made everything click for me.
Ok, this looks interesting. I'm going to do some further reading tomorrow. Are you recommending to use a ViewModel like: class PersonViewModel { object[] Items = { new CarsViewModel(), new HobbiesViewModel() } ? Thus creating a ViewModel for every TreeViewItem I want to display?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.