Treeview SelectedItem is sometimes VM, and sometimes TreeViewItem

I have a TreeView that the user moves to select an item to display in the grid. In short, XAML looks like this:

    <local:TreeViewEx x:Name="theTreeView" ItemsSource="{Binding theData}">

                        <local:TreeViewEx.ItemTemplate>
                            <sdk:HierarchicalDataTemplate ItemsSource="{Binding theChildData}">
                                <TextBlock Text="{Binding Name}"/>
                            </sdk:HierarchicalDataTemplate>
                        </local:TreeViewEx.ItemTemplate>
                    </local:TreeViewEx>

 <Grid DataContext="{Binding ElementName=theTreeView, Path=SelectedItem}">
                            <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding}" />
                    <TextBlock Text="{Binding Name}" /></StackPanel>
        </Grid>

As the user clicks on the tree, the name of the viewmodel type is displayed along with the value of the Name property. Fine. A Howerver user can also search for a tree image (following Josh Smith ), which sets the IsSelected TreeViewItem property. Once this happens, {Binding}the TreeViewItemEx displays, not the name of the ViewModel type, and, of course, the Name property is not displayed.

How is it possible that selectedItem can sometimes be a ViewModel, and sometimes a TreeViewItem?

+3
1

ContentControl, DataTemplateSelector.

<ContentControl Content="{Binding ElementName=theTreeView, Path=SelectedItem}" 
                ContentTemplateSelector="{StaticResource TreeViewItemSelector}" />

DataTemplateSelector

    <DataTemplate x:Key="ModelTemplate">
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding}" />
            <TextBlock Text="{Binding Name}" />
        </StackPanel>
    </DataTemplate>

    <TreeViewItemSelector x:Key="TreeViewItemSelector"
                          ModelTemplate="{StaticResource ModelTemplate}"
                          TreeItemTemplate="{StaticResource TreeItemTemplate}" />

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is ModelType)
            return ModelTemplate;
        if (item is TreeViewItem)
            return TreeItemTemplate;
        throw new NotImplementedException();
    }
+1

Source: https://habr.com/ru/post/1763988/


All Articles