Articles in this section
Category / Section

How to customize TreeView ItemTemplate based on the node in Xamarin.Forms (SfTreeView)

1 min read

You can customize the TreeView ItemTemplate based on the node by using DataTemplateSelector in Xamarin.Forms.

XAML

Binding ItemTemplateSelector to TreeView ItemTemplate.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:syncfusion="clr-namespace:Syncfusion.XForms.TreeView;assembly=Syncfusion.SfTreeView.XForms"
             xmlns:local="clr-namespace:TreeViewXamarin"
             x:Class="TreeViewXamarin.MainPage">
 
    <ContentPage.BindingContext>
        <local:FileManagerViewModel x:Name="viewModel"/>
    </ContentPage.BindingContext>
 
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:ItemTemplateSelector x:Key="ItemTemplateSelector" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <syncfusion:SfTreeView x:Name="treeView" Indentation="15" AutoExpandMode="AllNodesExpanded" ItemTemplateContextType="Node" 
                               ChildPropertyName="SubFiles" ItemsSource="{Binding ImageNodeInfo}" ItemTemplate="{StaticResource ItemTemplateSelector}"/>
 
    </ContentPage.Content>
</ContentPage>

C#

Apply template to node based on SubFiles.

namespace TreeViewXamarin
{
    public class ItemTemplateSelector : DataTemplateSelector
    {
        public DataTemplate _ParentTemplate { get; set; }
        public DataTemplate _ChildTemplate { get; set; }
        public ItemTemplateSelector()
        {
            this._ParentTemplate = new DataTemplate(typeof(ParentTemplate));
            this._ChildTemplate = new DataTemplate(typeof(ChildTemplate));
        }
        protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
        {
            var node = item as TreeViewNode;
            var treeviewItem = node.Content as FileManager;
            if (treeviewItem == null)
                return null;
            if (treeviewItem.SubFiles!=null)
                return _ParentTemplate;
            else
                return _ChildTemplate;
        }
    }
}

Output

TemplateSelector in TreeView

View Sample in GitHub

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied