Search code examples
c#wpfxamltreeviewtreeviewitem

Getting a class property from a data bound treeview on treeviewitem click


I'm having a problem, and no matter how much surfing stackoverflow and other parts of the internet I can't seem to get a right answer. I have a treeview which is bound to a List<Category> and my Category class is as below;

public class Category
{
    public string Name { get; set; }
    public dynamic SearchEngine { get; set; }
}

public class SearchEngine
{
    public virtual string IKey { get; set; }
    public virtual string IValue { get; set; }
    public virtual string icon { get; set; }
}

Now, the TreeView is using a custom template which is looking like this;

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=ItemList}" ItemTemplate="{StaticResource ResourceKey=childrenDataTemplate}">
        <Border BorderThickness="0" Margin="5">
            <TextBlock Text="{Binding Path=Name}" />
        </Border>
        <HierarchicalDataTemplate.ItemContainerStyle>
            <Style TargetType="TreeViewItem" BasedOn="{StaticResource TreeViewItem}">
                <Setter Property="FontWeight" Value="Normal"/>
                <Setter Property="Focusable" Value="True"/>
            </Style>
        </HierarchicalDataTemplate.ItemContainerStyle>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

<TreeView.ItemContainerStyle>
    <Style TargetType="TreeViewItem" BasedOn="{StaticResource TreeViewItem}">
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Focusable" Value="False"/>
    </Style>
</TreeView.ItemContainerStyle>

As you can see I've got TreeViewItemSelected bound in my TreeView object, and I'm able to alert a messagebox when selection is changed. I would like to get IValue on selection and pass it to another function to do something with. I've looked into SelectedItem but can't seem to find a way to get to the underlying data source.

Any tips? Thanks.


Solution

  • Have you tried this:

    void HandleSelected(object sender, RoutedEventArgs e)
        {
            var tvi = e.Source as TreeViewItem;
            var category = tvi.DataContext as Category;
            ...
        }