Category / Section
How to bind JSON data to Xamarin.Forms TreeView (SfTreeView)
1 min read
You can bind the data from JSON (JavaScript Object Notation) file to the Xamarin forms SfTreeView using ItemSource property.
STEP 1: Create a JSON data model
public class Cities { public string Name { get; set; } } public class States { public List<Cities> Cities { get; set; } public string Name { get; set; } } public class Countries { public List<States> States { get; set; } public string Name { get; set; } }
STEP 2: Accessed the JSON file from local folder and use StreamReader to reads the data and return as a ObservableCollection property.
private void GenerateSource() { var assembly = typeof(MainPage).GetTypeInfo().Assembly; Stream stream = assembly.GetManifestResourceStream("TreeViewXamarin.Data.navigation.json"); using (StreamReader sr = new StreamReader(stream)) { var jsonText = sr.ReadToEnd(); ImageNodeInfo = new ObservableCollection<Countries>(); var MyArrayData = JsonConvert.DeserializeObject<List<Countries>>(jsonText); foreach (var data in MyArrayData) { ImageNodeInfo.Add(data); } } }
STEP 3: Bind the JSON collection data to the SfTreeView ItemSource.
<syncfusion:SfTreeView x:Name="treeView" ItemHeight="40" Indentation="30" ExpanderWidth="20" ItemsSource="{Binding ImageNodeInfo}" AutoExpandMode="RootNodesExpanded" NodePopulationMode="Instant"> <syncfusion:SfTreeView.HierarchyPropertyDescriptors> <syncfusion1:HierarchyPropertyDescriptor TargetType="{x:Type local:Countries}" ChildPropertyName="States"/> <syncfusion1:HierarchyPropertyDescriptor TargetType="{x:Type local:States}" ChildPropertyName="Cities"/> </syncfusion:SfTreeView.HierarchyPropertyDescriptors> <syncfusion:SfTreeView.ItemTemplate> <DataTemplate> <ViewCell> <Grid x:Name="grid" BackgroundColor="Transparent"> <Label LineBreakMode="WordWrap" Text="{Binding Name}" TextColor="Black" VerticalTextAlignment="Center"/> </Grid> </ViewCell> </DataTemplate> </syncfusion:SfTreeView.ItemTemplate> </syncfusion:SfTreeView>
Output