开发者

How do I display index of a TreeViewItem within the ItemTemplate xaml?

开发者 https://www.devze.com 2023-04-11 12:17 出处:网络
I have a TreeView that uses an DataTemplate to customize the appearance of each item contained within the TreeView. Within the DataTemplate, I want to display the index of the relevant item within the

I have a TreeView that uses an DataTemplate to customize the appearance of each item contained within the TreeView. Within the DataTemplate, I want to display the index of the relevant item within the Treeview. What is the best way to approach this? Would a specific {Binding Path=""} allow me to get the index of the item?

My TreeView:

 <TreeView Name="_myTreeView"
      ItemsSource="{Binding [SourceCollection]}" 
      ItemTemplate="{StaticResource x:ResourceKey=MyTemplate}"
 />

My DataTemplate:

 <DataTemplate x:Key="MyTemplate">
      <Grid Margin="5,5,5,5">
          <Grid.RowDefinitions>
              <RowDefinition/>
              <RowDefinition/>
          </Grid.RowDefinitions>
          <TextBlock Grid.Row="0" Source="{Binding Path=IconPath}"/>
          <TextBlock Grid.Row="1" Text="{Binding Path=Caption}"/>
          <TextBlock Grid.Row="2" Text="{Binding Path=[SomePath]}"/>
        </Grid>
</DataTemplate>

Where [SourceCollection] is the source that the Tree draws it data from, and [SomePath] is the Binding Path I want to use to display the index of the item within the Tree. I'm open to taking a different approach entirely if my current method is an 开发者_Python百科inadvisable way to achieve this goal.


You can set AlternationCount to int.MaxValue on the TreeView, and bind to the ItemsControl.AlternationIndex attached property in the template.

<TextBlock Grid.Row="2" Text="{Binding Path=ItemsControl.AlternationIndex}"/>


I ended up adding a new property to items in my SourceCollection. This new property stores the index value that I was looking for.

Requirements for this application changed such that a simple integer index was insufficient. Adding a new property was the best way to go here. The index is updated after each change operation on the Tree.

0

精彩评论

暂无评论...
验证码 换一张
取 消