Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeView binding issue in WPF

Tags:

wpf

xaml

treeview

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

like image 370
Michael Stoll Avatar asked Nov 22 '25 05:11

Michael Stoll


1 Answers

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

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

like image 108
gn22 Avatar answered Nov 24 '25 09:11

gn22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!