views:

526

answers:

1

I have a very flat-structured treeview with only two levels of items - the main ones, and one level of subitems. I am using WPF MVVM and would like a way to style the two levels differently, but have no idea how.

I bind the treeview to an ObservableCollection in my ViewModel, and each element has one more ObservableCollection for the next level.

Any help?

+4  A: 

This can be accomplished via DATABINDING and using DATATEMPLATES.

You would design two DataTemplates. 1 as a Hierarchical DataTemplate and the other as a standard version for your lower level (this is since you only utilize 2 levels)

Then set the ItemTemplate of your HierarchicalDataTemplate to the regular DataTemplate

Details can be found here: http://msdn.microsoft.com/en-us/magazine/cc700358.aspx

Code snippet from the above site:

 <!-- ORDER DETAIL TEMPLATE -->
    <DataTemplate x:Key="OrderDetailTemplate">
      <TextBlock>
        <Run>Product:</Run>
        <TextBlock Text="{Binding Path=Product}" />
        <Run>(</Run>
        <TextBlock Text="{Binding Path=Quantity}" />
        <Run>)</Run>
      </TextBlock>
    </DataTemplate>

    <!-- ORDER TEMPLATE -->
    <HierarchicalDataTemplate 
      x:Key="OrderTemplate"
      ItemsSource="{Binding Path=OrderDetails}"
      ItemTemplate="{StaticResource OrderDetailTemplate}"
      >
      <TextBlock Text="{Binding Path=Desc}" />
    </HierarchicalDataTemplate>
Stephen Wrighton