Category / Section
How to keep the TreeView nodes expanded and collapsed states while navigating in Xamarin.Forms
You can keep the expander state of the TreeViewNode after navigation by using a model class property and updating its value whenever the node is expanded/collapsed in Xamarin.Forms SfTreeView.
XAML
Define behavior to the SfTreeView to update the expander state.
<syncfusion:SfTreeView x:Name="treeView"
ExpanderWidth="0"
Indentation="40"
ExpandActionTarget="Node"
ChildPropertyName="SubFiles"
ItemTemplateContextType="Node"
ItemsSource="{Binding ImageNodeInfo}">
<syncfusion:SfTreeView.Behaviors>
<local:TreeViewBehavior/>
</syncfusion:SfTreeView.Behaviors>
<syncfusion:SfTreeView.ItemTemplate>
<DataTemplate>
<Grid x:Name="grid" RowSpacing="0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40" />
<ColumnDefinition Width="40" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="{Binding IsExpanded, Converter={StaticResource ExpanderIconConverter}}"
IsVisible="{Binding HasChildNodes,Converter={StaticResource ExpanderIconVisibilityConverter}}"/>
<Image Grid.Column="1" Source="{Binding Content.ImageIcon}" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="35" WidthRequest="35"/>
<Grid Grid.Column="2" RowSpacing="1" Padding="1,0,0,0" VerticalOptions="Center">
<Label LineBreakMode="NoWrap" Text="{Binding ., Converter={x:StaticResource ExpanderStateConverer}}" VerticalTextAlignment="Center"/>
</Grid>
</Grid>
</DataTemplate>
</syncfusion:SfTreeView.ItemTemplate>
</syncfusion:SfTreeView>
C#
Update the model class IsExpanded property with the TreeViewNode.IsExpanded value in the NodeExpanded and NodeCollapsed events.
public class TreeViewBehavior : Behavior<SfTreeView>
{
protected override void OnAttachedTo(SfTreeView bindable)
{
bindable.NodeExpanded += Bindable_NodeExpanded;
bindable.NodeCollapsed += Bindable_NodeCollapsed;
base.OnAttachedTo(bindable);
}
private void Bindable_NodeCollapsed(object sender, NodeExpandedCollapsedEventArgs e)
{
(e.Node.Content as FileManager).IsExpanded = e.Node.IsExpanded;
}
private void Bindable_NodeExpanded(object sender, NodeExpandedCollapsedEventArgs e)
{
(e.Node.Content as FileManager).IsExpanded = e.Node.IsExpanded;
}
}
C#
While navigating back to the TreeView, you can use custom converters to keep the state of each TreeViewNode by using the data model property.
public class ExpanderStateConverer : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return null;
var treeViewNode = value as Syncfusion.TreeView.Engine.TreeViewNode;
var dataObject = treeViewNode.Content as FileManager;
treeViewNode.IsExpanded = dataObject.IsExpanded;
return dataObject.ItemName;
}
}
