How to use DataTemplateSelector on TreeViewItem's template?

不羁岁月 提交于 2021-01-29 06:10:10

问题


I have a TreeView with a custom resource dictionary for its TreeViewItems template.

I need to be able to programatically change the template for each TreeViewItem based on its binding's value.

As far as I can tell, I can't access the binding from the ResourceDictionary xaml.

I think I need to extend the TreeView with my own userControl, but I'm not sure what I need to actually add to it to achieve what I want.

Thanks in advance.

<TreeView Name="dirTree" AlternationCount="2" Background="#FAFAFA"
                       ScrollViewer.VerticalScrollBarVisibility ="Visible"
              VerticalAlignment="Stretch"
              ItemsSource="{Binding}"
              VirtualizingStackPanel.IsVirtualizing="False"
              VirtualizingStackPanel.VirtualizationMode="Standard"
              ItemTemplateSelector="{StaticResource tuningDataTemplateSelector}">
            <TreeView.Resources>
                <ResourceDictionary Source="UI/Styles/TunerTreeViewStyle.xaml" />
            </TreeView.Resources>

        </TreeView>

This is the treeview, and as you can see I have an ItemTemplateSelector set, but this only changes the contents. I need to add a selector for the TreeViewItem control's template itself. So I would need to add it to the TunerTreeViewStyle.xaml but I don't think you can get the bound data from there.


回答1:


You can't use an ItemTemplateSelector to change the ControlTemplate of a TreeViewItem.

If you want to do this you could try to define an ItemContainerStyle with a DataTrigger that sets the Template property of the TreeViewItem based on some source property, e.g.:

<TreeView>
    <TreeView.Resources>
        <Style TargetType="TreeViewItem">
            <Style.Triggers>
                <DataTrigger Binding="{Binding YourProperty}" Value="A">
                    <Setter Property="Template" Value="{StaticResource ResourceA}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding YourProperty}" Value="B">
                    <Setter Property="Template" Value="{StaticResource ResourceB}" />
                </DataTrigger>
                <!-- ... -->
            </Style.Triggers>
        </Style>
    </TreeView.Resources>
</TreeView>


来源:https://stackoverflow.com/questions/51285661/how-to-use-datatemplateselector-on-treeviewitems-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!