Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Treeview Item Root uses different template then child nodes

I currently am trying to bind my business object to a treeview as the root. And its collection property as the child. [I want to achieve this via BINDING]

Something like this.

public object MyBusinessObject
{
   private int _number;
   private bool _isSelected;
   private ObservableCollection<AnotherObject> _other = new ObservableCollection<AnotherObject>();


   public int Number { get {return _number;} set {_number = value;}}
   public bool IsSelected{ get {return _isSelected;} set {_isSelected= value;}}
   public ObservableCollection<AnotherObject>  Children { get {return _other;}}

}

I want my treeview to be represented like this:

  • "CheckBox binded to IsSelected" "Text binded to Number"
    • List of child binded to my "Children"
    • List of child binded to my "Children"
    • List of child binded to my "Children"
  • "CheckBox binded to IsSelected" "Text binded to Number"
    • List of child binded to my "Children"
    • List of child binded to my "Children"
    • List of child binded to my "Children"

I have no idea how to do this in xaml:

  <TreeView x:Name="_tv" ItemsSource="{Binding Path=MyBusinessObject}" >

            <TreeView.Resources>
                <HierarchicalDataTemplate> 
                    <CheckBox Content="{Binding Path=Number} IsChecked="{Binding Path=IsSelected}" />
                </HierarchicalDataTemplate>

                <HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
                    <TextBlock Text="{Binding Path=Name}" />
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>

I know the above is not right, but i was wondering if there is a way to do this properly.

Thanks and Regards,

like image 613
Kev84 Avatar asked Jan 12 '11 21:01

Kev84


1 Answers

Sure, you can use the HierarchicalDataTemplate.ItemTemplate property to define the data template to be used for the collection of AnotherObject instances.

<TreeView ItemsSource="{Binding SomeCollectionOfObjects}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">

            <!-- This is used for your AnotherObject instances -->
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>

            <!-- This is used for your MyBusinessObject instances -->
            <CheckBox Content="{Binding Number}" IsChecked="{Binding IsSelected}" />

        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>
like image 57
Josh Avatar answered Sep 22 '22 10:09

Josh