
Syncfusion Blazor Treemap
- 194 installs
- 4 repo stars
- Updated July 28, 2026
- syncfusion/blazor-ui-components-skills
Use syncfusion-blazor-treemap for development tasks
About
syncfusion-blazor-treemap: A skill for development. This provides functionality for development workflows.
- syncfusion-blazor-treemap
Syncfusion Blazor Treemap by the numbers
- 194 all-time installs (skills.sh)
- +13 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #2,058 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/syncfusion/blazor-ui-components-skills --skill syncfusion-blazor-treemapAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 194 |
|---|---|
| repo stars | ★ 4 |
| Last updated | July 28, 2026 |
| Repository | syncfusion/blazor-ui-components-skills ↗ |
What it does
Use syncfusion-blazor-treemap for development tasks
Files
Implementing TreeMap
NuGet: Syncfusion.Blazor.TreeMap + Syncfusion.Blazor.Themes Namespace: Syncfusion.Blazor.TreeMap
This skill collects all guidance for implementing the Syncfusion Blazor TreeMap component. Use the navigation guide below to open the specific reference topic you need; each reference file is self-contained and includes examples, edge cases, and troubleshooting.
Official API Surface
- Component:
SfTreeMap<TValue> - Interface:
ITreeMap - Core child settings:
TreeMapLevels,TreeMapLeafItemSettings,TreeMapLegendSettings,TreeMapTooltipSettings,TreeMapSelectionSettings,TreeMapHighlightSettings,TreeMapEvents - Common enums:
LayoutMode,RenderingMode,LabelPosition,LabelPlacement,LabelIntersectAction,LegendMode,LegendPosition,LegendOrientation,LegendShape,SelectionMode,HighLightMode - Common event args:
LoadEventArgs,LoadedEventArgs,ItemRenderingEventArgs,ItemClickEventArgs,ItemSelectedEventArgs,ItemMoveEventArgs,LegendRenderingEventArgs,LegendItemRenderingEventArgs,TreeMapTooltipArgs
When to Use This Skill
- When integrating a hierarchical, area-proportional visualization in a Blazor app.
- When you need guidance on layouts, color-mapping, labels, legends, or drill-down.
- When configuring data-binding for hierarchical or flat datasets.
- When implementing accessibility, localization, print/export, or performance optimizations.
⚠️ Security Warning
DO NOT bind TreeMap to untrusted public APIs or third-party data sources without proper validation. Remote data can be manipulated to inject malicious code, corrupt visualizations, or cause denial-of-service attacks. Always:
- ✅ Use only internal, authenticated APIs you own and control
- ✅ Validate and sanitize ALL remote data before binding
- ✅ Implement server-side authorization and rate limiting
- ✅ Use HTTPS and verify SSL/TLS certificates
- ✅ HTML-encode string properties to prevent XSS
For detailed security guidance, see: Security Considerations in data-binding.md
Documentation and Navigation Guide
API Reference
📄 Read: references/api-reference.md
- Quick lookup for the main TreeMap component, child settings, events, methods, and enums.
Getting Started
📄 Read: references/getting-started.md
- Installation, NuGet package, project setup, minimal example.
Data Binding and Sources
📄 Read: references/data-binding.md
- Flat vs hierarchical data, local/remote sources, data adaptors.
- Remote data binding: Only to internal, authenticated APIs you control — do NOT bind directly to untrusted third-party endpoints. See references/data-binding.md for the mandatory security checklist and safe patterns (server-side proxying, validation, sanitization, rate limits).
Layout and Levels
📄 Read: references/layout-and-levels.md
- Layout algorithms, level grouping, headers and gaps.
Leaf Items
📄 Read: references/leaf-items.md
- Leaf node styling, templates and label positioning.
Color Mapping
📄 Read: references/color-mapping.md
- Range, equal, desaturation, palette mappings and strategies.
Labels
📄 Read: references/labels.md
- Data label templates, formatting and overflow handling.
Legend
📄 Read: references/legend.md
- Legend modes, positioning and smart legend behaviors.
Tooltips
📄 Read: references/tooltip.md
- Default and templated tooltips, styling and dynamic content.
Drill-Down
📄 Read: references/drill-down.md
- Enabling drill-down, breadcrumbs, and custom navigation.
Selection & Highlight
📄 Read: references/selection-and-highlight.md
- Selection modes, highlight, and programmatic selection.
Events & Methods
📄 Read: references/events-and-methods.md
- Lifecycle events, render events, print/export methods.
Advanced Features
📄 Read: references/advanced-features.md
- Accessibility, localization, performance, placing the TreeMap inside other components.
Troubleshooting
📄 Read: references/troubleshooting.md
- Common issues, rendering and data-binding fixes.
Quick Start (Minimal example)
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@Data">
<TreeMapLevels>
<TreeMapLevel GroupPath="Category" />
</TreeMapLevels>
</SfTreeMap>
@code {
public object[] Data = new[] { new { Category = "A", Value = 10 } };
}Common Patterns
- Quick selection + drill-down for hierarchical exploration.
- Use
RangeColorMappingfor value-driven coloring andPalettewhen mapping explicit colors. - Prefer server-side paging/aggregation for very large datasets and use client-side rendering for moderate datasets.
References
- All reference files are in
references/and are self-contained with TOCs.
---
Implementing Syncfusion Blazor TreeMap
A comprehensive guide for implementing hierarchical data visualization using Syncfusion Blazor TreeMap component. TreeMaps display hierarchical data as nested rectangles where the size and color of each rectangle represents different data dimensions.
When to Use This Skill
Use this skill when you need to:
- Visualize hierarchical data structures - Display organizational charts, file systems, or nested data with parent-child relationships
- Show proportional data - Represent data where rectangle size reflects quantitative values (sales, population, disk space)
- Enable drill-down navigation - Allow users to interactively explore multi-level hierarchical data
- Compare data distributions - Use color mapping to show additional dimensions (growth, performance, categories)
- Display large datasets - Efficiently visualize hundreds or thousands of data points in limited space
- Create interactive dashboards - Combine with selection, highlighting, tooltips, and legends for rich user experience
Common Use Cases:
- Portfolio analysis and asset allocation
- Market share and competitive analysis
- Budget and resource distribution
- File/folder size visualization
- Organizational structure displays
- Product category sales analysis
- Website analytics (page hierarchy and traffic)
Component Overview
The TreeMap component organizes data into nested rectangles using various layout algorithms (Squarified, SliceDiceAuto, Horizontal, Vertical). Each rectangle's size is proportional to a specified data value, and colors can represent additional dimensions through sophisticated color mapping strategies.
Key Capabilities:
- Multiple layout algorithms for optimal space utilization
- Hierarchical data binding (flat or nested structures)
- Multi-level drill-down with breadcrumb navigation
- Advanced color mapping (range, equal, desaturation, palette)
- Interactive legends with filtering
- Rich tooltips with templates
- Selection and highlight modes
- Print and export (PDF, PNG, JPEG, SVG)
- Full accessibility support (ARIA, keyboard navigation)
Documentation and Navigation Guide
Getting Started
📄 Read: references/getting-started.md
When to read: Setting up TreeMap for the first time, installation, basic implementation
What's covered:
- Installation via Visual Studio, VS Code, or .NET CLI
- NuGet package setup (Syncfusion.Blazor.TreeMap)
- Service registration and namespace imports
- CSS theme configuration
- Basic TreeMap implementation with sample data
- License registration for production
- Blazor WebAssembly vs Web App differences
Data Binding and Sources
📄 Read: references/data-binding.md
When to read: Connecting TreeMap to data sources, handling different data structures
What's covered:
- Flat data structure vs hierarchical data structure
- Local data binding (collections, JSON files)
- Remote data binding with authentication and authorization
- Security considerations - Only bind to trusted internal APIs with proper authentication
- WeightValuePath and RangeColorValuePath configuration
- Handling nested objects and complex data
- Entity Framework integration
- Data transformation techniques
- Best practices for large datasets
Layout and Hierarchy
📄 Read: references/layout-and-levels.md
When to read: Configuring TreeMap appearance, multi-level structures
What's covered:
- Layout algorithms (Squarified, SliceDiceAuto, Horizontal, Vertical)
- When to use each layout type
- Multi-level TreeMap configuration
- Level-specific customization (headers, borders, colors)
- GroupPath for hierarchical data organization
- Gap and border configuration
- Header templates and positioning
Leaf Items
📄 Read: references/leaf-items.md
When to read: Customizing individual TreeMap rectangles (leaf nodes)
What's covered:
- Leaf item styling and appearance
- Label formatting and positioning
- Template-based customization
- Gap, border, and color configuration
- Show/hide labels
- Overflow handling
- Interactive leaf patterns
Color Mapping
📄 Read: references/color-mapping.md
When to read: Applying colors to represent data dimensions, creating heat maps
What's covered:
- Range color mapping (gradients based on value ranges)
- Equal color mapping (distinct colors per category)
- Desaturation color mapping (intensity variations)
- Desaturation with multiple colors
- Palette color mapping
- Binding colors directly from data source
- Handling items excluded from color mapping
- Custom color strategies
Labels
📄 Read: references/labels.md
When to read: Adding text labels to TreeMap items
What's covered:
- Data label configuration and formatting
- Label positioning options (Center, TopLeft, TopCenter, etc.)
- Font customization
- Label templates with custom content
- Smart label positioning (trim, hide, wrap)
- Format strings and data binding
- Responsive label behavior
Legend
📄 Read: references/legend.md
When to read: Adding legends for color mapping interpretation
What's covered:
- Legend modes (Default, Interactive, Smart)
- Legend positioning and alignment
- Legend customization (colors, shapes, text)
- Smart legend with toggle functionality
- Legend templates for custom rendering
- Visibility control
- Legend integration with color mappings
Tooltips
📄 Read: references/tooltip.md
When to read: Adding hover information to TreeMap items
What's covered:
- Default tooltip configuration
- Tooltip templates with custom HTML/Blazor components
- Styling and formatting
- Dynamic tooltip content based on data
- Tooltip positioning and animation
- Format strings for values
- Tooltips for different data structures
Drill-Down Navigation
📄 Read: references/drill-down.md
When to read: Enabling interactive hierarchical navigation
What's covered:
- Enabling drill-down on item click
- Breadcrumb navigation configuration
- Header customization for drill-down
- Programmatic drill-down control
- Drill-down events (ItemClick, DrillStart, DrillEnd)
- Resetting to initial view
- Multi-level navigation patterns
Selection and Highlight
📄 Read: references/selection-and-highlight.md
When to read: Adding user interaction for selecting/highlighting items
What's covered:
- Selection modes (Item, Child, Parent, All)
- Single vs multiple selection
- Highlight on hover configuration
- Customizing selection appearance (colors, borders, opacity)
- Programmatic selection
- Selection events (ItemSelected)
- Combining selection with drill-down
Events and Methods
📄 Read: references/events-and-methods.md
When to read: Handling user interactions, lifecycle events, or invoking component methods
What's covered:
- Component lifecycle events (Loaded, BeforeRender)
- User interaction events (ItemClick, ItemSelected, ItemHighlight)
- Rendering events (ItemRendering, TooltipRender, LegendRender)
- Drill-down events (DrillStart, DrillEnd)
- Print() and Export() methods (PDF, PNG, JPEG, SVG)
- Refresh() and other utility methods
- Event handling patterns and best practices
Advanced Features
📄 Read: references/advanced-features.md
When to read: Implementing print/export, localization, accessibility, or performance optimization
What's covered:
- Print and export functionality (PDF, PNG, JPEG, SVG)
- Internationalization and localization
- RTL (right-to-left) support
- Accessibility features (ARIA, keyboard navigation, screen readers)
- Performance optimization techniques
- Responsive design patterns
- Embedding TreeMap in other components
- CSP (Content Security Policy) compliance
Quick Start Example
Here's a minimal working example to get started:
@page "/treemap-demo"
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@GrowthReports"
WeightValuePath="GDP"
TValue="Country">
<TreeMapLeafItemSettings LabelPath="Name">
</TreeMapLeafItemSettings>
</SfTreeMap>
@code {
public class Country
{
public string Name { get; set; }
public double GDP { get; set; }
}
private List<Country> GrowthReports = new List<Country>
{
new Country { Name = "United States", GDP = 17946 },
new Country { Name = "China", GDP = 10866 },
new Country { Name = "Japan", GDP = 4123 },
new Country { Name = "Germany", GDP = 3355 },
new Country { Name = "United Kingdom", GDP = 2848 }
};
}Prerequisites:
- Install
Syncfusion.Blazor.TreeMapNuGet package - Register services in
Program.cs:builder.Services.AddSyncfusionBlazor(); - Add theme CSS reference in layout file
- Register Syncfusion license for production use
Common Patterns
Pattern 1: Hierarchical Data with Color Mapping
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@SalesData"
WeightValuePath="Sales"
RangeColorValuePath="Growth"
TValue="Region">
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafLabelStyle Color="#FFFFFF"></TreeMapLeafLabelStyle>
</TreeMapLeafItemSettings>
<TreeMapLegendSettings Visible="true" Position="@using Syncfusion.Blazor.TreeMap.LegendPosition.Top">
</TreeMapLegendSettings>
<TreeMapLevels>
<TreeMapLevel GroupPath="Continent" HeaderFormat="${Continent} - ${Sales}">
<TreeMapLevelBorder Color="#FFFFFF" Width="1"></TreeMapLevelBorder>
</TreeMapLevel>
</TreeMapLevels>
<TreeMapRangeColorMappings>
<TreeMapRangeColorMapping From="0" To="5" Color="@("#70AD47")" />
<TreeMapRangeColorMapping From="5" To="10" Color="@("#FFC000")" />
<TreeMapRangeColorMapping From="10" To="20" Color="@("#FF5722")" />
</TreeMapRangeColorMappings>
</SfTreeMap>Use when: Displaying hierarchical business data with performance indicators
Pattern 2: Drill-Down with Breadcrumb Navigation
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@OrganizationData"
WeightValuePath="EmployeeCount"
EnableDrillDown="true"
TValue="Department">
<TreeMapLeafItemSettings LabelPath="Name">
</TreeMapLeafItemSettings>
<TreeMapBreadcrumbSettings Visible="true">
</TreeMapBreadcrumbSettings>
<TreeMapLevels>
<TreeMapLevel GroupPath="Division" HeaderFormat="${Division}">
</TreeMapLevel>
<TreeMapLevel GroupPath="Team" HeaderFormat="${Team}">
</TreeMapLevel>
</TreeMapLevels>
</SfTreeMap>Use when: Users need to navigate through multi-level organizational or hierarchical data
Pattern 3: Interactive TreeMap with Selection and Tooltips
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@PortfolioData"
WeightValuePath="Value"
TValue="Investment">
<TreeMapLeafItemSettings LabelPath="Name">
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true">
<Template>
@{
var data = context as Investment;
<div style="padding:5px;background:#fff;border:1px solid #ccc">
<b>@data.Name</b><br/>
Value: $@data.Value.ToString("N0")<br/>
Return: @data.Return%
</div>
}
</Template>
</TreeMapTooltipSettings>
<TreeMapSelectionSettings Enable="true" Fill="#58a0d3" Opacity="0.8">
</TreeMapSelectionSettings>
<TreeMapHighlightSettings Enable="true" Fill="#e5e5e5" Opacity="0.6">
</TreeMapHighlightSettings>
</SfTreeMap>Use when: Building interactive dashboards requiring user engagement
Pattern 4: Squarified Layout with Custom Palette
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@Categories"
WeightValuePath="Sales"
LayoutType="LayoutMode.Squarified"
Palette="@(new string[] {"#9999ff", "#CBCBCB", "#E8DAFF", "#E4E4E4"})"
TValue="Category">
<TreeMapLeafItemSettings LabelPath="Name" Fill="#8ebfe2">
<TreeMapLeafBorder Color="#FFFFFF" Width="2"></TreeMapLeafBorder>
</TreeMapLeafItemSettings>
<TreeMapTitleSettings Text="Product Category Sales">
</TreeMapTitleSettings>
</SfTreeMap>Use when: Creating visually distinct category comparisons
Key Props and Configuration
Essential Properties:
| Property | Type | Purpose |
|---|---|---|
DataSource | IEnumerable<TValue> | Data collection to bind |
WeightValuePath | string | Property determining rectangle size |
RangeColorValuePath | string | Property for color mapping values |
TValue | Type | Generic type of data items |
LayoutType | LayoutMode | Layout algorithm (Squarified, SliceDiceAuto, etc.) |
EnableDrillDown | bool | Enable hierarchical navigation |
Palette | string[] | Color palette for items |
Child Components:
TreeMapLeafItemSettings- Leaf node configurationTreeMapLevels- Multi-level hierarchyTreeMapRangeColorMappings/TreeMapEqualColorMappings- Color strategiesTreeMapLegendSettings- Legend configurationTreeMapTooltipSettings- Tooltip configurationTreeMapSelectionSettings- Selection behaviorTreeMapHighlightSettings- Hover effects
Related Skills
- HeatMap Chart - For matrix-based heat map visualization
- For other data visualization components, explore the Data Visualization category
Troubleshooting Quick Tips
- TreeMap not rendering: Ensure NuGet package is installed, services are registered, and CSS theme is referenced
- Data not displaying: Verify
WeightValuePathmatches a numeric property in your data model - Colors not applying: Check that
RangeColorValuePathis set and color mappings are properly configured - Drill-down not working: Set
EnableDrillDown="true"and configureTreeMapLevelswithGroupPath - Performance issues: For large datasets (>1000 items), consider pagination or hierarchical loading with drill-down
For comprehensive details on any topic, refer to the appropriate reference file listed in the navigation guide above.
Advanced Features
Table of Contents
- Overview
- Print and Export
- Internationalization
- Accessibility
- Performance Tips
- Placing inside other components
Overview
Advanced topics such as exporting, localization, accessibility and performance optimizations.
Print and Export
- Use the component's printing and export APIs to create PDFs or images of the TreeMap.
Internationalization
- Localize labels and templates; support RTL where required.
Accessibility
- Configure ARIA attributes, keyboard navigation, and screen reader text for TreeMap items.
Performance Tips
- Aggregate or page very large datasets server-side; minimize DOM updates and templates for thousands of items.
Placing inside other components
- Use the provided examples to embed TreeMap inside layouts, dialogs, or other Syncfusion components.
API Reference
Table of Contents
- Overview
- Component Model
- Core Properties
- Child Components
- Events
- Methods
- Enums and Supporting Types
- Related Guides
Overview
This page summarizes the main Syncfusion Blazor TreeMap API surface used throughout the skill. It is intended as a quick reference for the component, its child configuration objects, supported events, public methods, and the enums that appear across the topic guides.
Component Model
- Namespace:
Syncfusion.Blazor.TreeMap - Main component:
SfTreeMap<TValue> - Interface:
ITreeMap - Primary purpose: render hierarchical, area-proportional data as nested rectangles.
Core Properties
These are the most commonly used SfTreeMap<TValue> members across the skill:
DataSource- source collection for TreeMap items.TValue- the data model type bound to the component.WeightValuePath- numeric value used to determine rectangle size.ColorValuePath- value path used for color-based rendering.RangeColorValuePath- value path used with range color mapping.EqualColorValuePath- value path used with equal color mapping.Palette- explicit color palette.LayoutType- layout algorithm such asLayoutMode.Squarified.RenderDirection- rectangle rendering direction.HeightandWidth- component dimensions.EnableDrillDown- enables hierarchical drill-down.EnableRtl- enables right-to-left rendering.
Other commonly used configuration containers include TreeMapLegendSettings, TreeMapTooltipSettings, TreeMapSelectionSettings, TreeMapHighlightSettings, TreeMapTitleSettings, TreeMapSubtitleSettings, and TreeMapMargin.
Child Components
TreeMap configuration is composed through nested child settings. The most important ones are:
TreeMapLevels- container for one or moreTreeMapLevelitems.TreeMapLevel- defines a hierarchy level and its header styling.TreeMapLevelBorder- level border settings.TreeMapLeafItemSettings- leaf-node styling and label configuration.TreeMapLeafLabelStyle- leaf label text styling.TreeMapLeafBorder- leaf border styling.TreeMapLeafColorMapping- single leaf color mapping entry.TreeMapLeafColorMappings- collection of leaf color mappings.TreeMapLegendSettings- legend configuration.TreeMapLegendBorder- legend border styling.TreeMapLegendLocation- legend placement and offset configuration.TreeMapLegendTitle- legend title configuration.TreeMapLegendTextStyle- legend text styling.TreeMapLegendTitleStyle- legend title text styling.TreeMapLegendShapeBorder- border styling for legend shapes.TreeMapTooltipSettings- tooltip configuration.TreeMapTooltipBorder- tooltip border styling.TreeMapTooltipTextStyle- tooltip text styling.TreeMapSelectionSettings- selection behavior and appearance.TreeMapHighlightSettings- highlight behavior and appearance.TreeMapTitleSettings- title configuration.TreeMapSubtitleSettings- subtitle configuration.TreeMapBorderSettings- component border settings.TreeMapMargin- spacing around the TreeMap.TreeMapInitialDrillSettings- initial drill-down state.TreeMapEvents- event callbacks.
Events
TreeMapEvents exposes the callbacks used across the topic guides:
LoadLoadedItemRenderingItemSelectedLegendRenderingLegendItemRenderingOnClickOnDoubleClickOnDrillStartOnItemClickOnItemMoveOnPrintOnRightClickResizingTooltipRenderingDrillCompletedItemHighlighted
Common event argument types include:
LoadEventArgsLoadedEventArgsItemRenderingEventArgsItemClickEventArgsItemSelectedEventArgsItemMoveEventArgsItemHighlightEventArgsLegendRenderingEventArgsLegendItemRenderingEventArgsTreeMapTooltipArgsPrintEventArgsRightClickEventArgsClickEventArgsDoubleClickEventArgsDrillStartEventArgsDrillEndEventArgsResizeEventArgs
Methods
Common SfTreeMap<TValue> methods used in the skill:
ExportAsync()- exports the TreeMap output.PrintAsync()- prints the TreeMap.RefreshAsync()- refreshes the component.SelectItemAsync()- selects a TreeMap item programmatically.
Enums and Supporting Types
The following enums and supporting types appear throughout the references:
Layout and Rendering
LayoutModeRenderingModeRenderDirection
Legends
LegendModeLegendPositionLegendOrientationLegendShape
Labels
LabelPositionLabelPlacementLabelIntersectAction
Interaction
SelectionModeHighLightMode
General UI
AlignmentExportType
Related Guides
- Getting Started
- Data Binding
- Layout and Levels
- Leaf Items
- Color Mapping
- Labels
- Legend
- Tooltips
- Drill-Down
- Selection and Highlight
- Events and Methods
- Advanced Features
Color Mapping
Table of Contents
- Overview
- Range Color Mapping
- Equal Color Mapping
- Desaturation Mapping
- Palette Mapping
- Binding Colors from Data
Overview
Describes strategies to map colors to TreeMap items based on numeric ranges or explicit color values in data.
Range Color Mapping
- Define ranges with start/end and corresponding colors to visualize value gradients.
Equal Color Mapping
- Map discrete value buckets to fixed colors.
Desaturation Mapping
- Use desaturation techniques for subtle value gradations across a palette.
Palette Mapping
- Provide an explicit palette array for categorical coloring.
Binding Colors from Data
- Bind a color field from your data when each item already contains a color value.
Color Mapping in Blazor TreeMap Component
Table of Contents
- Overview
- Color Mapping Types
- Range Color Mapping
- Basic Range Mapping
- Multiple Ranges
- Edge Cases and Overlaps
- Equal Color Mapping
- Categorical Data Coloring
- Multiple Categories
- Desaturation Color Mapping
- Single Color Desaturation
- Opacity Range Configuration
- Desaturation with Multiple Colors
- Gradient Effects
- Multi-Color Ranges
- Palette Color Mapping
- Using Palette Arrays
- Built-in Palettes
- Binding Colors from Data
- Handling Excluded Items
- Combining Color Mapping Techniques
- Troubleshooting
- Best Practices
Overview
Color mapping is a powerful feature that allows you to customize the color of TreeMap items based on data values or categories. It provides visual differentiation, highlights important data points, and creates intuitive data visualizations. The TreeMap component supports multiple color mapping strategies, each suited for different data types and visualization goals.
Why Use Color Mapping?
- Visual data segmentation
- Highlighting ranges or thresholds
- Categorical differentiation
- Creating heat maps
- Improving data readability
- Emphasizing outliers
Color Mapping Types
The Blazor TreeMap supports five primary color mapping approaches:
| Type | Use Case | Data Type | Color Source |
|---|---|---|---|
| Range | Numeric ranges and thresholds | Numeric | Configuration |
| Equal | Categorical grouping | String/Enum | Configuration |
| Desaturation | Gradient within ranges | Numeric | Opacity variation |
| Palette | Automatic distribution | Any | Predefined array |
| ColorValuePath | Direct data binding | Any | Data property |
Range Color Mapping
Range color mapping applies colors based on numeric value ranges using the RangeColorValuePath property to evaluate data values. Define mapping ranges with StartRange and EndRange properties, and specify colors using the Color property. Perfect for creating heat maps and highlighting thresholds.
Basic Range Mapping
Define color ranges using the StartRange and EndRange properties within TreeMapLeafColorMapping components. Set the RangeColorValuePath property at the SfTreeMap level to specify which data field will be evaluated against these ranges. Use the Color property to assign a color array for each range.
Example: Two-Range Color Mapping
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" TValue="Fruit"
DataSource="Fruits" RangeColorValuePath="Count">
<TreeMapLeafItemSettings LabelPath="FruitName">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping StartRange="500" EndRange="3000"
Color='new string[] { "Orange" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000" EndRange="5000"
Color='new string[] { "Green" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
</SfTreeMap>
@code {
public class Fruit
{
public string FruitName { get; set; }
public double Count { get; set; }
}
public List<Fruit> Fruits = new List<Fruit> {
new Fruit { FruitName="Apple", Count=5000 },
new Fruit { FruitName="Mango", Count=3000 },
new Fruit { FruitName="Orange", Count=2300 },
new Fruit { FruitName="Banana", Count=500 },
new Fruit { FruitName="Grape", Count=4300 },
new Fruit { FruitName="Papaya", Count=1200 },
new Fruit { FruitName="Melon", Count=4500 }
};
}Key Properties:
RangeColorValuePath: Specifies which data field contains values for range evaluationStartRange: Minimum value (inclusive)EndRange: Maximum value (inclusive)Color: Array of color strings
Multiple Ranges
Create sophisticated visualizations with multiple color ranges by defining multiple TreeMapLeafColorMapping components with different StartRange and EndRange values. Each mapping applies its Color property when the data value falls within that range. Define mappings in order, as the first matching range takes precedence.
Example: Five-Tier TreeMap
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Sales" TValue="Product"
DataSource="Products" RangeColorValuePath="Sales">
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<!-- Critical Low -->
<TreeMapLeafColorMapping StartRange="0" EndRange="1000"
Color='new string[] { "#D32F2F" }'>
</TreeMapLeafColorMapping>
<!-- Low -->
<TreeMapLeafColorMapping StartRange="1000" EndRange="2500"
Color='new string[] { "#FF9800" }'>
</TreeMapLeafColorMapping>
<!-- Medium -->
<TreeMapLeafColorMapping StartRange="2500" EndRange="4000"
Color='new string[] { "#FDD835" }'>
</TreeMapLeafColorMapping>
<!-- Good -->
<TreeMapLeafColorMapping StartRange="4000" EndRange="5500"
Color='new string[] { "#7CB342" }'>
</TreeMapLeafColorMapping>
<!-- Excellent -->
<TreeMapLeafColorMapping StartRange="5500" EndRange="8000"
Color='new string[] { "#388E3C" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true" Format="${Name}: ${Sales}">
</TreeMapTooltipSettings>
</SfTreeMap>
@code {
public class Product
{
public string Name { get; set; }
public double Sales { get; set; }
}
public List<Product> Products = new List<Product> {
new Product { Name="Product A", Sales=7500 },
new Product { Name="Product B", Sales=3200 },
new Product { Name="Product C", Sales=1200 },
new Product { Name="Product D", Sales=5800 },
new Product { Name="Product E", Sales=2100 }
};
}Edge Cases and Overlaps
Important Range Rules: 1. Ranges are inclusive on both ends 2. Value at exact boundary belongs to first matching range 3. Overlapping ranges: first match wins 4. Missing ranges use default fill color
Example: Handling Boundary Values
@using Syncfusion.Blazor.TreeMap
<!-- Value = 3000 will match first range due to inclusive EndRange -->
<TreeMapLeafColorMapping StartRange="500" EndRange="3000" Color='new string[] { "Orange" }'></TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000" EndRange="5000" Color='new string[] { "Green" }'></TreeMapLeafColorMapping>
<!-- Better: Use non-overlapping ranges -->
<TreeMapLeafColorMapping StartRange="500" EndRange="2999" Color='new string[] { "Orange" }'></TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000" EndRange="5000" Color='new string[] { "Green" }'></TreeMapLeafColorMapping>Equal Color Mapping
Equal color mapping assigns colors based on exact value matches using the EqualColorValuePath property to specify which data field contains categorical values. Use the LeafValue property to match specific values and the Color property to assign corresponding colors. Ideal for categorical data visualization.
Categorical Data Coloring
Map specific values to colors using the LeafValue property to match categorical values, and the Color property to assign the corresponding color. Set the EqualColorValuePath property at the SfTreeMap level to specify which data field contains the categorical values to be matched.
Example: Brand-Based Coloring
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" TValue="Car"
DataSource="Cars" EqualColorValuePath="Brand">
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping LeafValue="Ford"
Color='new string[] { "green" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping LeafValue="Audi"
Color='new string[] { "red" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping LeafValue="Maruti"
Color='new string[]{ "orange" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
</SfTreeMap>
@code {
public class Car
{
public string Name { get; set; }
public int Count { get; set; }
public string Brand { get; set; }
}
public List<Car> Cars = new List<Car> {
new Car { Name="Mustang", Brand="Ford", Count=232 },
new Car { Name="EcoSport", Brand="Ford", Count=121 },
new Car { Name="Swift", Brand="Maruti", Count=143 },
new Car { Name="Baleno", Brand="Maruti", Count=454 },
new Car { Name="Vitara Brezza", Brand="Maruti", Count=545 },
new Car { Name="A3 Cabriolet", Brand="Audi", Count=123 },
new Car { Name="RS7 Sportback", Brand="Audi", Count=523 }
};
}Multiple Categories
Handle complex categorical data with many distinct values by creating multiple TreeMapLeafColorMapping components. Use the LeafValue property for each category and the Color property to assign a specific color to that category. Set EqualColorValuePath to specify the data field containing these category values.
Example: Status-Based Coloring
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Amount" TValue="Transaction"
DataSource="Transactions" EqualColorValuePath="Status">
<TreeMapLeafItemSettings LabelPath="TransactionID">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping LeafValue="Completed"
Color='new string[] { "#4CAF50" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping LeafValue="Pending"
Color='new string[] { "#FFC107" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping LeafValue="Failed"
Color='new string[] { "#F44336" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping LeafValue="Cancelled"
Color='new string[] { "#9E9E9E" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping LeafValue="Processing"
Color='new string[] { "#2196F3" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true"
Format="${TransactionID}<br>Status: ${Status}<br>Amount: $${Amount}">
</TreeMapTooltipSettings>
</SfTreeMap>
@code {
public class Transaction
{
public string TransactionID { get; set; }
public double Amount { get; set; }
public string Status { get; set; }
}
public List<Transaction> Transactions = new List<Transaction> {
new Transaction { TransactionID="TXN001", Amount=5000, Status="Completed" },
new Transaction { TransactionID="TXN002", Amount=3200, Status="Pending" },
new Transaction { TransactionID="TXN003", Amount=1500, Status="Failed" },
new Transaction { TransactionID="TXN004", Amount=7800, Status="Completed" },
new Transaction { TransactionID="TXN005", Amount=2100, Status="Processing" },
new Transaction { TransactionID="TXN006", Amount=900, Status="Cancelled" }
};
}Equal Color Mapping Tips:
- Values must match exactly (case-sensitive)
- Undefined values use default fill color
- Works with strings, numbers, and enums
- Consider using enums for type safety
Desaturation Color Mapping
Desaturation creates gradient effects by varying opacity within color ranges using the MinOpacity and MaxOpacity properties. Combined with StartRange and EndRange properties, opacity values are applied linearly across the value range to create subtle color gradations.
Single Color Desaturation
Apply a single color with varying opacity based on value by specifying the Color property and using the MinOpacity and MaxOpacity properties within TreeMapLeafColorMapping. Define the range using StartRange and EndRange, and the opacity will vary linearly across that range.
Example: Opacity Gradient
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" TValue="Fruit"
DataSource="Fruits" RangeColorValuePath="Count">
<TreeMapLeafItemSettings LabelPath="FruitName">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping StartRange="500" EndRange="3000"
MinOpacity="0.2" MaxOpacity="0.5"
Color='new string[] { "Orange" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000" EndRange="5000"
MinOpacity="0.5" MaxOpacity="0.8"
Color='new string[] { "Green" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true" Format="${FruitName}: ${Count}">
</TreeMapTooltipSettings>
</SfTreeMap>Opacity Range Configuration
Opacity Properties:
MinOpacity: Starting opacity value (0.0 to 1.0) applied at theStartRangevalueMaxOpacity: Ending opacity value (0.0 to 1.0) applied at theEndRangevalue- Opacity is applied linearly across the value range defined by
StartRangeandEndRange - Works with any base color specified in the
Colorproperty - Used in conjunction with
StartRangeandEndRangefor range-based gradient effects
Calculating Opacity:
For a value V in range [StartRange, EndRange]:
Opacity = MinOpacity + ((V - StartRange) / (EndRange - StartRange)) * (MaxOpacity - MinOpacity)Example: Precise Opacity Control
@using Syncfusion.Blazor.TreeMap
<!-- Very Light to Medium -->
<TreeMapLeafColorMapping StartRange="0" EndRange="1000"
MinOpacity="0.1" MaxOpacity="0.4"
Color='new string[] { "#2196F3" }'>
</TreeMapLeafColorMapping>
<!-- Medium to Dark -->
<TreeMapLeafColorMapping StartRange="1000" EndRange="3000"
MinOpacity="0.4" MaxOpacity="0.7"
Color='new string[] { "#2196F3" }'>
</TreeMapLeafColorMapping>
<!-- Dark to Very Dark -->
<TreeMapLeafColorMapping StartRange="3000" EndRange="5000"
MinOpacity="0.7" MaxOpacity="1.0"
Color='new string[] { "#2196F3" }'>
</TreeMapLeafColorMapping>Desaturation with Multiple Colors
Create sophisticated gradient effects using multiple colors within a range.
Gradient Effects
When multiple colors are specified in the Color property as an array, the TreeMap creates smooth transitions between those colors. Combine with MinOpacity and MaxOpacity properties to create sophisticated gradient effects with opacity variations across the range defined by StartRange and EndRange.
Example: Two-Color Gradient
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" TValue="Fruit"
DataSource="Fruits" RangeColorValuePath="Count">
<TreeMapLeafItemSettings LabelPath="FruitName">
<TreeMapLeafColorMappings>
<!-- Orange to Pink gradient -->
<TreeMapLeafColorMapping StartRange="500" EndRange="3000"
MinOpacity="0.2" MaxOpacity="0.5"
Color='new string[]{ "orange", "pink" }'>
</TreeMapLeafColorMapping>
<!-- Three-color gradient: Green to Red to Blue -->
<TreeMapLeafColorMapping StartRange="3000" EndRange="5000"
MinOpacity="0.2" MaxOpacity="0.5"
Color='new string[]{ "green", "red", "blue" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
</SfTreeMap>Multi-Color Ranges
Use three or more colors in the Color property array for complex gradients. Define separate TreeMapLeafColorMapping components with different StartRange and EndRange values, each containing multiple colors in the Color property. Optionally use MinOpacity and MaxOpacity for additional opacity-based gradation.
Example: Temperature Heat Map
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Temperature" TValue="Location"
DataSource="WeatherData" RangeColorValuePath="Temperature">
<TreeMapLeafItemSettings LabelPath="City">
<TreeMapLeafColorMappings>
<!-- Cold: Blue to Cyan -->
<TreeMapLeafColorMapping StartRange="-20" EndRange="0"
MinOpacity="0.2" MaxOpacity="0.5"
Color='new string[]{ "#0D47A1", "#29B6F6" }'>
</TreeMapLeafColorMapping>
<!-- Cool to Mild: Cyan to Yellow -->
<TreeMapLeafColorMapping StartRange="0" EndRange="20"
MinOpacity="0.2" MaxOpacity="0.5"
Color='new string[]{ "#00BCD4", "#FFEB3B" }'>
</TreeMapLeafColorMapping>
<!-- Warm: Yellow to Orange -->
<TreeMapLeafColorMapping StartRange="20" EndRange="35"
MinOpacity="0.2" MaxOpacity="0.5"
Color='new string[]{ "#FFC107", "#FF5722" }'>
</TreeMapLeafColorMapping>
<!-- Hot: Orange to Red to Dark Red -->
<TreeMapLeafColorMapping StartRange="35" EndRange="50"
MinOpacity="0.2" MaxOpacity="0.5"
Color='new string[]{ "#FF5722", "#F44336", "#B71C1C" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true"
Format="${City}: ${Temperature}°C">
</TreeMapTooltipSettings>
</SfTreeMap>
@code {
public class Location
{
public string City { get; set; }
public double Temperature { get; set; }
}
public List<Location> WeatherData = new List<Location> {
new Location { City="Moscow", Temperature=-15 },
new Location { City="New York", Temperature=8 },
new Location { City="London", Temperature=12 },
new Location { City="Dubai", Temperature=42 },
new Location { City="Singapore", Temperature=30 }
};
}Palette Color Mapping
Palette mapping automatically distributes colors from a predefined array across all items using the Palette property. Define a color palette array at the TreeMap component level for automatic sequential color distribution to TreeMap elements.
Using Palette Arrays
Define a palette using the Palette property at the SfTreeMap level with an array of color values for automatic color distribution. The TreeMap will sequentially assign colors from the palette to items in the order they appear in the data source.
Example: Custom Palette
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" TValue="Car" DataSource="Cars"
Palette='new string[] { "#FFB3B3", "#2196F3", "#E67E22", "#9B59B6" }'>
<TreeMapLeafItemSettings LabelPath="Name">
</TreeMapLeafItemSettings>
</SfTreeMap>
@code {
public class Car
{
public string Name { get; set; }
public string Brand { get; set; }
public int Count { get; set; }
}
public List<Car> Cars = new List<Car> {
new Car { Name="Mustang", Brand="Ford", Count=232},
new Car { Name="EcoSport", Brand="Ford", Count=121},
new Car { Name="Swift", Brand="Maruti", Count=143},
new Car { Name="Baleno", Brand="Maruti", Count=454},
new Car { Name="Vitara Brezza", Brand="Maruti", Count=545},
new Car { Name="A3 Cabriolet", Brand="Audi", Count=123},
new Car { Name="RS7 Sportback", Brand="Audi", Count=523 }
};
}Built-in Palettes
Popular Palette Schemes:
@code {
// Material Design
string[] MaterialPalette = new string[] {
"#F44336", "#E91E63", "#9C27B0", "#673AB7",
"#3F51B5", "#2196F3", "#03A9F4", "#00BCD4"
};
// Flat UI
string[] FlatPalette = new string[] {
"#1ABC9C", "#2ECC71", "#3498DB", "#9B59B6",
"#34495E", "#F1C40F", "#E67E22", "#E74C3C"
};
// Gradient
string[] GradientPalette = new string[] {
"#C33764", "#AB3566", "#993367", "#853169",
"#742F6A", "#632D6C", "#532C6D", "#412A6F",
"#312870", "#1D2671"
};
// Monochrome Blue
string[] MonochromePalette = new string[] {
"#0D47A1", "#1565C0", "#1976D2", "#1E88E5",
"#2196F3", "#42A5F5", "#64B5F6", "#90CAF9"
};
}Binding Colors from Data
Directly bind colors from your data source by setting the ColorValuePath property to specify a data field containing color values. Each TreeMap item will use the color specified in its corresponding data record.
Example: Data-Driven Colors
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" TValue="Fruit"
DataSource="Fruits" ColorValuePath="Color">
<TreeMapLeafItemSettings LabelPath="Name">
</TreeMapLeafItemSettings>
<TreeMapLegendSettings Visible="true">
</TreeMapLegendSettings>
</SfTreeMap>
@code {
public class Fruit
{
public string Name { get; set; }
public double Count { get; set; }
public string Color { get; set; }
}
public List<Fruit> Fruits = new List<Fruit> {
new Fruit { Name="Apple", Count=5000, Color = "red" },
new Fruit { Name="Mango", Count=3000, Color="blue" },
new Fruit { Name="Orange", Count=2300, Color="green" },
new Fruit { Name="Banana", Count=500 , Color="yellow"},
new Fruit { Name="Grape", Count=4300 , Color="orange"},
new Fruit { Name="Papaya",Count=1200 , Color="pink"},
new Fruit { Name="Melon", Count=4500, Color="violet" }
};
}When to Use ColorValuePath:
- Dynamic color assignment
- User-customizable colors
- Colors from external sources
- Complex business logic for colors
- Database-driven color schemes
Handling Excluded Items
Items outside defined ranges can be assigned a specific color by creating a TreeMapLeafColorMapping without StartRange and EndRange properties. This catch-all mapping will apply its Color property to any values that don't match the defined range conditions.
Example: Catch-All Color for Unmapped Values
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" TValue="Fruit"
DataSource="Fruits" RangeColorValuePath="Count">
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<!-- Low Range -->
<TreeMapLeafColorMapping StartRange="500" EndRange="3000"
Color='new string[] { "Orange" }'>
</TreeMapLeafColorMapping>
<!-- Medium Range -->
<TreeMapLeafColorMapping StartRange="3000" EndRange="4000"
Color='new string[]{ "Green" }'>
</TreeMapLeafColorMapping>
<!-- Catch-all for values outside ranges (e.g., >4000) -->
<TreeMapLeafColorMapping Color='new string[]{ "purple" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
<TreeMapLegendSettings Visible="true">
</TreeMapLegendSettings>
</SfTreeMap>Rules for Excluded Items:
- Mapping without StartRange/EndRange catches all unmatched values
- Should be defined last in the mappings
- Useful for outliers or unexpected values
- Appears in legend if legend is enabled
Combining Color Mapping Techniques
Mix different color mapping strategies for complex visualizations by using multiple TreeMapLeafColorMapping components with different property combinations. Combine RangeColorValuePath with StartRange/EndRange mappings for specific ranges, and add a catch-all mapping using Color property without range properties. You can also use the Palette property alongside color mappings as a fallback.
Example: Range Mapping with Palette Fallback
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Sales" TValue="Product"
DataSource="Products"
RangeColorValuePath="Sales"
Palette='new string[] { "#95A5A6", "#7F8C8D" }'>
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<!-- High performers -->
<TreeMapLeafColorMapping StartRange="5000" EndRange="10000"
Color='new string[] { "#27AE60" }'>
</TreeMapLeafColorMapping>
<!-- Medium performers -->
<TreeMapLeafColorMapping StartRange="2000" EndRange="5000"
Color='new string[] { "#F39C12" }'>
</TreeMapLeafColorMapping>
<!-- Low performers (will use palette colors) -->
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
</SfTreeMap>Troubleshooting
Colors Not Applied
Problem: TreeMap shows default colors instead of mapped colors.
Solutions: 1. Verify RangeColorValuePath or EqualColorValuePath is set correctly 2. Check that color mapping is inside TreeMapLeafItemSettings 3. Ensure data values fall within defined ranges 4. Validate color values are valid CSS colors 5. Check for typos in property names
@code {
// Debug color mapping
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
foreach (var item in Fruits)
{
Console.WriteLine($"{item.Name}: Count={item.Count}");
}
}
}
}Equal Color Mapping Not Working
Problem: Categorical colors not displaying correctly.
Solutions: 1. Ensure EqualColorValuePath matches data property exactly 2. Check LeafValue matches data values (case-sensitive) 3. Verify data contains expected categorical values 4. Test with simple string values first
Desaturation Not Visible
Problem: Opacity gradient not apparent.
Solutions: 1. Increase difference between MinOpacity and MaxOpacity 2. Use darker base colors for better visibility 3. Check background color contrast 4. Ensure values span the full range 5. Verify opacity values are between 0.0 and 1.0
Legend Not Matching Colors
Problem: Legend shows different colors than TreeMap.
Solutions: 1. Ensure legend is enabled: <TreeMapLegendSettings Visible="true"> 2. Check if ShowLegend is set for color mappings 3. Verify color mapping configuration 4. Test with simpler color schemes
Best Practices
Range Color Mapping
1. ✅ Use non-overlapping ranges 2. ✅ Cover full expected data range 3. ✅ Provide catch-all for outliers 4. ✅ Use intuitive color progressions (light to dark) 5. ✅ Test with edge case values 6. ✅ Document range meanings
Equal Color Mapping
1. ✅ Use distinct, contrasting colors 2. ✅ Limit categories for clarity (< 10 recommended) 3. ✅ Consider colorblind-friendly palettes 4. ✅ Provide legend for category identification 5. ✅ Handle missing categories gracefully 6. ✅ Use semantic colors (red=danger, green=success)
Desaturation
1. ✅ Use opacity range of at least 0.3-0.4 difference 2. ✅ Start with MinOpacity ≥ 0.2 for visibility 3. ✅ Keep MaxOpacity ≤ 0.9 for label readability 4. ✅ Use darker colors for better gradient visibility 5. ✅ Test on different backgrounds
Palette Selection
1. ✅ Choose colors with sufficient contrast 2. ✅ Use 5-10 colors for optimal variety 3. ✅ Consider brand colors 4. ✅ Test accessibility (WCAG AA compliance) 5. ✅ Avoid overly bright or neon colors 6. ✅ Use established color schemes
Performance
1. ✅ Minimize number of color mappings 2. ✅ Avoid complex gradient calculations 3. ✅ Use simple color values (hex preferred) 4. ✅ Cache palette arrays 5. ✅ Test with maximum expected data size
Accessibility
1. ✅ Ensure 4.5:1 contrast ratio for text 2. ✅ Don't rely solely on color for information 3. ✅ Provide legends for color meanings 4. ✅ Use patterns in addition to colors when possible 5. ✅ Test with colorblind simulation tools 6. ✅ Support high contrast modes
Maintenance
1. ✅ Document color scheme meanings 2. ✅ Use constants for color values 3. ✅ Centralize palette definitions 4. ✅ Version control color schemes 5. ✅ Provide theme switching capability 6. ✅ Keep color logic separate from data logic
Data Binding
Table of Contents
Overview
This file explains how to bind flat and hierarchical data to the TreeMap, including common patterns for GroupPath, WeightValuePath, and transforming datasets.
Flat Data
- Provide an array of objects and set
WeightValuePathto the numeric value field.
Hierarchical Data
- Use
GroupPathor nested collections to represent levels. Flatten or adapt JSON when required.
Local and Remote Sources
- Local: in-memory collections or JSON files.
- Remote: fetch data only from trusted internal APIs (or local packaged files). Do NOT bind directly to untrusted third-party endpoints; proxy third-party feeds through a server where you can authenticate, validate, sanitize, and enforce rate limits and payload-size limits.
Data Adaptor Patterns
- Normalize remote responses to objects with
GroupPathandWeightValuePath.
Edge Cases
- Empty points, null values, and inconsistent nesting require sanitization before binding.
Data Binding in Blazor TreeMap Component
Table of Contents
- Overview
- Understanding Data Structures
- Flat Data Structure
- Hierarchical Data Structure
- Key Properties for Data Binding
- DataSource Property
- WeightValuePath
- RangeColorValuePath
- EqualColorValuePath
- ColorValuePath
- Local Data Binding
- Binding IEnumerable Collections
- Loading JSON Data
- Best Practices for Local Data
- Remote Data Binding
- Using SfDataManager
- OData Services
- OData V4 Services
- Web API Integration
- Entity Framework Integration
- Creating DBContext Class
- Data Access Layer
- Web API Controller Setup
- Binding TreeMap to Entity Framework
- Creating DBContext Class
- Data Access Layer
- Web API Controller Setup
- Binding TreeMap to Entity Framework
- Data Transformation Techniques
- Troubleshooting
- Performance Considerations
Overview
Data binding is the fundamental mechanism that connects your data source to the TreeMap component. The TreeMap uses the DataSource property to accept data in various formats, enabling visualization of hierarchical or flat data structures. Proper data binding ensures accurate representation of your data through size, color, and hierarchical organization of TreeMap items.
IMPORTANT: Security-first data binding policy
Do NOT bind the TreeMap directly to untrusted third-party endpoints or user-supplied URLs. The component can ingest remote data which may contain malicious payloads, large nested objects, or crafted values that can affect rendering, expose sensitive information, or cause denial-of-service. Follow these mandatory rules:
- Only bind to internal, authenticated APIs that you control, or to local/sample data packaged with the application.
- If you must use third-party data, proxy it through your server where you can validate, sanitize, and enforce rate limits and size caps.
- Never perform unauthenticated client-side fetches from arbitrary external hosts.
- Include server-side validation and sanitization for all numeric and string fields returned to the client.
- Keep the client-side examples in this repository limited to local sample data or clearly-labeled, internal API placeholders.
See the "Validation Checklist for Remote Data Binding" section for required server-side and deployment controls.
⚠️ Security Considerations for Data Binding
Third-Party Data Exposure Risk
When binding TreeMap to remote or third-party data sources (public APIs, OData endpoints, or external Web APIs), you expose your application to potential security risks:
Key Risks:
- Malicious Data Injection: Untrusted data can be crafted to execute unintended behavior
- XSS (Cross-Site Scripting): If data is rendered directly without sanitization, it can execute malicious scripts
- Data Tampering: Public APIs can be compromised or intercepted, leading to data integrity issues
- Visualization Manipulation: Malicious numeric or categorical data can skew charts or mislead users
- Performance Attacks: Large or nested payloads can cause DoS (Denial of Service) attacks
Security Best Practices
1. Only Bind to Trusted Internal APIs
- ✅ Your organization's internal APIs (with authentication)
- ✅ APIs you own and control
- ✅ Vetted third-party APIs with strong security records
- ❌ Do NOT use public/untrusted OData or demo endpoints
2. Always Use Authentication
Use JWT/OAuth 2.0 tokens with your API endpoints:
@code {
public Dictionary<string, string> AuthHeaders { get; set; }
protected override void OnInitialized()
{
AuthHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Bearer {GetSecureToken()}" }
};
}
private string GetSecureToken()
{
// Retrieve JWT token from secure authentication service
return "your-jwt-token";
}
}3. Implement Server-Side Data Validation
Add validation and sanitization on your backend API:
[Authorize]
[HttpGet("api/orders")]
public async Task<IActionResult> GetOrders()
{
// Get authenticated user
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId))
return Unauthorized();
// Fetch data with user-specific authorization
var orders = await db.Orders
.Where(o => o.UserId == userId)
.ToListAsync();
// Validate and sanitize data before returning
foreach (var order in orders)
{
// Clamp numeric values
if (order.Freight < 0) order.Freight = 0;
if (order.Freight > 100000) order.Freight = 100000;
// HTML-encode string properties
order.ShipCity = System.Web.HttpUtility.HtmlEncode(order.ShipCity);
}
return Ok(orders);
}4. Use HTTPS Only
- Always use
https://URLs for all API endpoints - Ensure your application validates SSL/TLS certificates
- In production, consider certificate pinning for critical APIs
When to Use Remote Data Binding Safely
Safe Scenarios:
- ✅ Binding to your organization's internal APIs with proper authentication
- ✅ Public APIs with data you own and control
- ✅ Third-party APIs with strong track records and security certifications
- ✅ APIs behind corporate firewalls and VPNs
- ✅ APIs that return validated and sanitized data
Unsafe Scenarios:
- ❌ Completely untrusted public APIs
- ❌ User-supplied API URLs without validation
- ❌ APIs without proper authentication/authorization
- ❌ APIs that return unvalidated HTML or JavaScript
- ❌ APIs with no rate limiting or abuse protection
Validation Checklist for Remote Data Binding
- [ ] API endpoint uses HTTPS
- [ ] API requires authentication (JWT, OAuth 2.0, etc.)
- [ ] API has authorization controls
- [ ] Data is validated on server-side before returning to client
- [ ] Response payload size is limited (pagination implemented)
- [ ] Rate limiting is enforced
- [ ] Request/response logging is enabled for audit trails
- [ ] CORS is properly configured with specific origins
- [ ] Client-side sanitization of display data is implemented
- [ ] Error responses don't expose sensitive information
Understanding Data Structures
Flat Data Structure
Flat data represents a simple list of items without nested relationships. Each item in the collection is at the same level, making it ideal for visualizing simple datasets where hierarchy is not required.
When to use flat data:
- Single-level categorization
- Simple comparisons across items
- Direct property mapping without nesting
Example: GDP Comparison
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="GDP" TValue="GDPReport" DataSource="GrowthReports">
<TreeMapLeafItemSettings LabelPath="Country">
</TreeMapLeafItemSettings>
</SfTreeMap>
@code {
public class GDPReport
{
public string Country { get; set; }
public double GDP { get; set; }
public double Percentage { get; set; }
public double Rank { get; set; }
}
public List<GDPReport> GrowthReports = new List<GDPReport> {
new GDPReport {Country = "United States", GDP=17946, Percentage=11.08, Rank=1},
new GDPReport {Country="China", GDP=10866, Percentage= 28.42, Rank=2},
new GDPReport {Country="Japan", GDP=4123, Percentage=-30.78, Rank=3},
new GDPReport {Country="Germany", GDP=3355, Percentage=-5.19, Rank=4},
new GDPReport {Country="United Kingdom", GDP=2848, Percentage=8.28, Rank=5},
new GDPReport {Country="France", GDP=2421, Percentage=-9.69, Rank=6},
new GDPReport {Country="India", GDP=2073, Percentage=13.65, Rank=7},
new GDPReport {Country="Italy", GDP=1814, Percentage=-12.45, Rank=8},
new GDPReport {Country="Brazil", GDP=1774, Percentage=-27.88, Rank=9},
new GDPReport {Country="Canada", GDP=1550, Percentage=-15.02, Rank=10}
};
}Hierarchical Data Structure
Hierarchical data represents nested relationships where items can contain child items at multiple levels. This structure is perfect for visualizing organizational data, geographical regions, or any multi-level categorization.
When to use hierarchical data:
- Multi-level organizational structures
- Nested categorizations
- Drill-down requirements
- Parent-child relationships
Example: Population by Continent and States
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Population" DataSource="PopulationReport">
<TreeMapLeafItemSettings LabelPath="Name" Fill="#0077b3">
<TreeMapLeafBorder Width="0.5" Color="black"></TreeMapLeafBorder>
</TreeMapLeafItemSettings>
<TreeMapLevels>
<TreeMapLevel GroupPath="Continent" Fill="#004466">
<TreeMapLevelBorder Width="0.5" Color="black"></TreeMapLevelBorder>
</TreeMapLevel>
<TreeMapLevel GroupPath="States" Fill="#0099e6">
<TreeMapLevelBorder Width="0.5" Color="black"></TreeMapLevelBorder>
</TreeMapLevel>
</TreeMapLevels>
</SfTreeMap>
@code{
public List<object> PopulationReport { get; set; } = new List<object>
{
new {
Continent = new List<object> { new {
Name= "Africa",
Population= 1216130000,
States= new List<object> { new {
Name= "Eastern Africa",
Population= 410637987,
Region= new List<object> { new {
Name= "Ethiopia",
Population= 107534882
}}
},
new {
Name= "Middle Africa",
Population= 158562976,
Region= new List<object>{ new {
Name= "Democratic, Republic of the Congo",
Population= 84004989
}}
}
}
}}
},
new {
Continent= new List<object> { new {
Name= "Asia",
Population= 4436224000,
States= new List<object> { new {
Name= "Central Asia",
Population= 69787760,
Region= new List<object> { new {
Name= "Uzbekistan",
Population= 32364996
}}
},
new {
Name= "Eastern Asia",
Population= 1641908531,
Region= new List<object> { new {
Name= "China",
Population= 1415045928
}}
}
}
}}
}
};
}Key Difference: Flat data uses simple properties, while hierarchical data uses nested collections with List<object> or custom typed collections.
Key Properties for Data Binding
DataSource Property
The DataSource property is the primary mechanism for providing data to the TreeMap. It accepts various collection types:
List<T>- Strongly typed listsIEnumerable<T>- Any enumerable collectionobjectcollections - For hierarchical dataSfDataManager- For remote data sources
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@MyDataCollection" TValue="MyDataType" WeightValuePath="Value">
</SfTreeMap>Important: Always specify the TValue generic parameter to match your data type.
WeightValuePath
The WeightValuePath property determines the size of each TreeMap item. It should reference a numeric property in your data source.
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="GDP" TValue="GDPReport" DataSource="GrowthReports">
</SfTreeMap>Rules:
- Must reference a numeric property (int, double, decimal, float)
- Larger values create larger rectangles
- Cannot be null or negative
- Zero values create items with minimal size
RangeColorValuePath
Used with range color mapping to apply colors based on numeric value ranges. This property specifies which data field contains the values for color determination.
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" RangeColorValuePath="Count"
TValue="Fruit" DataSource="Fruits">
<TreeMapLeafItemSettings LabelPath="FruitName">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping StartRange="500" EndRange="3000"
Color='new string[] { "Orange" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000" EndRange="5000"
Color='new string[] { "Green" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
</SfTreeMap>EqualColorValuePath
Used with equal color mapping to apply specific colors to items with matching values. Ideal for categorical data.
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" EqualColorValuePath="Brand"
TValue="Car" DataSource="Cars">
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping LeafValue="Ford" Color='new string[] { "green" }'>
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping LeafValue="Audi" Color='new string[] { "red" }'>
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
</SfTreeMap>ColorValuePath
Directly binds colors from the data source, allowing each item to have its own color specified in the data.
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="Count" ColorValuePath="Color"
TValue="Fruit" DataSource="Fruits">
<TreeMapLeafItemSettings LabelPath="Name"></TreeMapLeafItemSettings>
</SfTreeMap>
@code {
public class Fruit
{
public string Name { get; set; }
public double Count { get; set; }
public string Color { get; set; }
}
public List<Fruit> Fruits = new List<Fruit> {
new Fruit { Name="Apple", Count=5000, Color = "red" },
new Fruit { Name="Mango", Count=3000, Color="blue" },
new Fruit { Name="Orange", Count=2300, Color="green" }
};
}Local Data Binding
Binding IEnumerable Collections
The TreeMap component works seamlessly with any IEnumerable collection, including List, Array, ObservableCollection, and custom collections.
Example: Using List with Palette
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="GrowthReports" TValue="GDPReport"
Palette="@Palette" WeightValuePath="GDP">
<TreeMapLeafItemSettings LabelPath="CountryName">
<TreeMapLeafLabelStyle Color="White"></TreeMapLeafLabelStyle>
</TreeMapLeafItemSettings>
</SfTreeMap>
@code{
public class GDPReport
{
public string CountryName { get; set; }
public double GDP { get; set; }
public double Percentage { get; set; }
public int Rank { get; set; }
}
public string[] Palette = new string[] { "#87CEFA", "#87CEEB" };
public List<GDPReport> GrowthReports = new List<GDPReport> {
new GDPReport {CountryName="United States", GDP=17946, Percentage=11.08, Rank=1},
new GDPReport {CountryName="China", GDP=10866, Percentage= 28.42, Rank=2},
new GDPReport {CountryName="Japan", GDP=4123, Percentage=-30.78, Rank=3},
new GDPReport {CountryName="Germany", GDP=3355, Percentage=-5.19, Rank=4},
new GDPReport {CountryName="United Kingdom", GDP=2848, Percentage=8.28, Rank=5},
new GDPReport {CountryName="France", GDP=2421, Percentage=-9.69, Rank=6},
new GDPReport {CountryName="India", GDP=2073, Percentage=13.65, Rank=7},
new GDPReport {CountryName="Italy", GDP=1814, Percentage=-12.45, Rank=8},
new GDPReport {CountryName="Brazil", GDP=1774, Percentage=-27.88, Rank=9},
new GDPReport {CountryName="Canada", GDP=1550, Percentage=-15.02, Rank=10}
};
}Loading JSON Data
For scenarios where data is stored in JSON files, use HttpClient to fetch and deserialize the data.
@using Syncfusion.Blazor.TreeMap
@inject NavigationManager Navigation
@inject HttpClient Http
@if (GrowthReports == null)
{
<p><em>Loading TreeMap component...</em></p>
}
else
{
<SfTreeMap WeightValuePath="GDP" TValue="GDPReport" DataSource="GrowthReports">
<TreeMapLeafItemSettings LabelPath="Country">
</TreeMapLeafItemSettings>
</SfTreeMap>
}
@code{
public List<GDPReport> GrowthReports { get; set; }
protected async override Task OnInitializedAsync()
{
try
{
// Use only local packaged JSON or your own secure, authenticated APIs.
// Never fetch arbitrary third-party URLs from the client.
GrowthReports = await Http.GetFromJsonAsync<List<GDPReport>>(Navigation.ToAbsoluteUri("sample-data/product-growth.json"));
// Basic client-side validation/sanitization (do not rely on client checks alone)
if (GrowthReports == null)
GrowthReports = new List<GDPReport>();
foreach (var item in GrowthReports)
{
if (item.GDP < 0) item.GDP = 0;
item.Country = System.Net.WebUtility.HtmlEncode(item.Country ?? string.Empty);
}
}
catch (Exception)
{
// Loading failed: prefer showing a safe fallback and logging the error.
GrowthReports = new List<GDPReport>();
}
}
public class GDPReport
{
public string Country { get; set; }
public int GDP { get; set; }
public double Percentage { get; set; }
public int Rank { get; set; }
}
}JSON File Structure (sample-data/product-growth.json):
[
{"Country": "United States", "GDP": 17946, "Percentage": 11.08, "Rank": 1},
{"Country": "China", "GDP": 10866, "Percentage": 28.42, "Rank": 2},
{"Country": "Japan", "GDP": 4123, "Percentage": -30.78, "Rank": 3}
]Best Practices for Local Data
1. Use strongly-typed collections for compile-time safety 2. Initialize data in OnInitializedAsync for async operations 3. Handle null checks before rendering TreeMap 4. Use loading indicators during data fetch 5. Implement error handling for failed data loads
@code{
protected override async Task OnInitializedAsync()
{
try
{
GrowthReports = await LoadDataAsync();
}
catch (Exception ex)
{
ErrorMessage = $"Failed to load data: {ex.Message}";
}
}
}Remote Data Binding
⚠️ Security Warning: Remote Data Sources
Before proceeding with remote data binding, review the [Security Considerations section](#️-security-considerations-for-data-binding) above.
Do NOT bind TreeMap to untrusted public APIs. Always validate, sanitize, and authenticate remote data sources. Only bind to APIs you own, control, or explicitly trust.
Using SfDataManager
The SfDataManager component provides a unified interface for accessing remote data sources. When using SfDataManager, you must explicitly specify the TValue parameter.
Key Points:
- Supports multiple adaptors (OData, ODataV4, WebApi, Url)
- Handles query operations automatically
- Provides built-in error handling
- Supports paging and filtering
- MUST be paired with server-side validation and authorization
OData Services (Internal APIs Only)
OData (Open Data Protocol) is a standardized REST-based protocol for querying and updating data. Only use with internal, authenticated APIs.
@using Syncfusion.Blazor.TreeMap
@using Syncfusion.Blazor.Data
<!-- ✅ SECURE: Uses internal API with authentication -->
<SfTreeMap TValue="OrderDetails" WeightValuePath="Freight" Palette="@Palette">
<SfDataManager Url="https://your-internal-api.yourdomain.com/api/odata/orders"
Adaptor="Syncfusion.Blazor.Adaptors.ODataAdaptor"
Headers="@AuthHeaders">
</SfDataManager>
<TreeMapTitleSettings Text="Order Details">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="ShipCountry">
<TreeMapLeafBorder Color="white" Width="0.5">
</TreeMapLeafBorder>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true">
</TreeMapTooltipSettings>
</SfTreeMap>
@code{
public string[] Palette = new string[] {
"#C33764", "#AB3566", "#993367", "#853169",
"#742F6A", "#632D6C", "#532C6D", "#412A6F",
"#312870", "#1D2671"
};
// Include authentication headers
public Dictionary<string, string> AuthHeaders { get; set; }
protected override void OnInitialized()
{
AuthHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Bearer {GetSecureToken()}" }
};
}
private string GetSecureToken()
{
// Retrieve JWT token from secure storage
// Never hardcode tokens!
return "your-jwt-token";
}
public class OrderDetails
{
public int OrderID { get; set; }
public string OrderDate { get; set; }
public string CustomerID { get; set; }
public string ShipCountry { get; set; }
public double Freight { get; set; }
}
}OData V4 Services (Internal APIs Only)
OData V4 is an enhanced version of OData with improved functionality and performance. Use only with internal, authenticated APIs.
@using Syncfusion.Blazor.TreeMap
@using Syncfusion.Blazor.Data
<!-- ✅ SECURE: Uses internal API with authentication -->
<SfTreeMap TValue="OrderDetails" WeightValuePath="Freight" Palette="@Palette">
<SfDataManager Url="https://your-internal-api.yourdomain.com/api/odata/v4/orders"
Adaptor="Syncfusion.Blazor.Adaptors.ODataV4Adaptor"
Headers="@AuthHeaders">
</SfDataManager>
<TreeMapTitleSettings Text="Order Details">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="ShipCountry">
<TreeMapLeafBorder Color="white" Width="0.5">
</TreeMapLeafBorder>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true"></TreeMapTooltipSettings>
</SfTreeMap>
@code{
public string[] Palette = new string[] {
"#C33764", "#AB3566", "#993367", "#853169",
"#742F6A", "#632D6C", "#532C6D", "#412A6F",
"#312870", "#1D2671"
};
public Dictionary<string, string> AuthHeaders { get; set; }
protected override void OnInitialized()
{
AuthHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Bearer {GetSecureToken()}" }
};
}
private string GetSecureToken()
{
// Retrieve from secure authentication service
return "your-jwt-token";
}
public class OrderDetails
{
public int OrderID { get; set; }
public string OrderDate { get; set; }
public string CustomerID { get; set; }
public string ShipCountry { get; set; }
public double Freight { get; set; }
}
}Web API Integration (Recommended Secure Approach)
Use WebApiAdaptor with your own backend Web API that implements proper security controls.
@using Syncfusion.Blazor.TreeMap
@using Syncfusion.Blazor.Data
<!-- ✅ SECURE: Uses your backend API with auth headers -->
<SfTreeMap TValue="OrderDetails" WeightValuePath="Freight" Palette="@Palette">
<SfDataManager Url="https://your-domain.com/api/secure/orders"
Adaptor="Syncfusion.Blazor.Adaptors.WebApiAdaptor"
Headers="@AuthHeaders">
</SfDataManager>
<TreeMapTitleSettings Text="Order Details">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="ShipCity">
<TreeMapLeafBorder Color="white" Width="0.5">
</TreeMapLeafBorder>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true">
</TreeMapTooltipSettings>
</SfTreeMap>
@code{
public string[] Palette = new string[] {
"#C33764", "#AB3566", "#993367", "#853169",
"#742F6A", "#632D6C", "#532C6D", "#412A6F",
"#312870", "#1D2671"
};
public Dictionary<string, string> AuthHeaders { get; set; }
protected override void OnInitialized()
{
AuthHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Bearer {GetSecureToken()}" }
};
}
private string GetSecureToken()
{
// Retrieve JWT from secure service
return "your-jwt-token";
}
public class OrderDetails
{
public int OrderID { get; set; }
public string OrderDate { get; set; }
public string CustomerID { get; set; }
public string ShipCity { get; set; }
public double Freight { get; set; }
}
}Backend API Controller with Security:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace YourApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize] // Require authentication
public class SecureOrdersController : ControllerBase
{
private readonly IOrderService _orderService;
public SecureOrdersController(IOrderService orderService)
{
_orderService = orderService;
}
[HttpGet("orders")]
public async Task<ActionResult<IEnumerable<OrderDetails>>> GetOrders()
{
try
{
// Get authenticated user
var userId = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId))
return Unauthorized("User not authenticated");
// Fetch data with user-specific authorization
var orders = await _orderService.GetUserOrdersAsync(userId);
// Validate and sanitize data
ValidateOrders(orders);
return Ok(orders);
}
catch (Exception ex)
{
// Log error securely (never expose stack trace to client)
LogError(ex);
return StatusCode(500, "An error occurred retrieving orders");
}
}
private void ValidateOrders(List<OrderDetails> orders)
{
foreach (var order in orders)
{
// Validate numeric ranges
if (order.Freight < 0) order.Freight = 0;
if (order.Freight > 100000) order.Freight = 100000;
// Sanitize string properties
order.ShipCity = System.Web.HttpUtility.HtmlEncode(order.ShipCity);
order.CustomerID = System.Web.HttpUtility.HtmlEncode(order.CustomerID);
}
}
private void LogError(Exception ex)
{
// Log to application log, not to client response
System.Diagnostics.Debug.WriteLine($"Error retrieving orders: {ex.Message}");
}
}
}Entity Framework Integration
Creating DBContext Class
Create a DBContext class to establish a connection to your Microsoft SQL Server database.
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFTreeMap.Data;
namespace EFTreeMap.Data
{
public class OrderContext : DbContext
{
public virtual DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
// Configure the context to connect to a Microsoft SQL Server database
optionsBuilder.UseSqlServer(
@"Data Source=(LocalDB)\MSSQLLocalDB;
AttachDbFilename='D:\blazor\EFTreeMap\App_Data\NORTHWND.MDF';
Integrated Security=True;Connect Timeout=30");
}
}
}
public class Order
{
[Key]
public int? OrderID { get; set; }
[Required]
public string CustomerID { get; set; }
[Required]
public int EmployeeID { get; set; }
}
}Data Access Layer
Create a data access layer to retrieve records from the database table.
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFTreeMap.Data;
namespace EFTreeMap.Data
{
public class OrderDataAccessLayer
{
OrderContext db = new OrderContext();
// Get all Orders details
public DbSet<Order> GetAllOrders()
{
try
{
return db.Orders;
}
catch
{
throw;
}
}
}
}Web API Controller Setup
Create a Web API Controller that allows the TreeMap to consume data from Entity Framework.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using EFTreeMap.Data;
namespace EFTreeMap.Controller
{
[Route("api/[controller]")]
[ApiController]
public class DefaultController : ControllerBase
{
OrderDataAccessLayer db = new OrderDataAccessLayer();
[HttpGet]
public object Get()
{
IQueryable<Order> data = db.GetAllOrders().AsQueryable();
var count = data.Count();
var queryString = Request.Query;
if (queryString.Keys.Contains("$inlinecount"))
{
StringValues Skip;
StringValues Take;
int skip = (queryString.TryGetValue("$skip", out Skip)) ?
Convert.ToInt32(Skip[0]) : 0;
int top = (queryString.TryGetValue("$top", out Take)) ?
Convert.ToInt32(Take[0]) : data.Count();
return new { Items = data.Skip(skip).Take(top), Count = count };
}
else
{
return data;
}
}
}
}Binding TreeMap to Entity Framework
Method 1: Direct Binding
@inject OrderDataAccessLayer OrderData
@using EFTreeMap.Data
@using Syncfusion.Blazor.TreeMap
<SfTreeMap TValue="Order" WeightValuePath="OrderID"
Palette="@Palette" DataSource="@OrderData.GetAllOrders()">
<TreeMapTitleSettings Text="Order Details">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="CustomerID">
<TreeMapLeafBorder Color="white" Width="0.5">
</TreeMapLeafBorder>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true"></TreeMapTooltipSettings>
</SfTreeMap>
@code{
public string[] Palette = new string[] {
"#C33764", "#AB3566", "#993367", "#853169",
"#742F6A", "#632D6C", "#532C6D", "#412A6F",
"#312870", "#1D2671"
};
}Method 2: Using Web API with SfDataManager
@using Syncfusion.Blazor.TreeMap
@using Syncfusion.Blazor.Data
<SfTreeMap TValue="Order" WeightValuePath="OrderID" Palette="@Palette">
<SfDataManager Url="api/Default"
Adaptor="Syncfusion.Blazor.Adaptors.WebApiAdaptor">
</SfDataManager>
<TreeMapTitleSettings Text="Order Details">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="CustomerID">
<TreeMapLeafBorder Color="white" Width="0.5">
</TreeMapLeafBorder>
</TreeMapLeafItemSettings>
<TreeMapTooltipSettings Visible="true"></TreeMapTooltipSettings>
</SfTreeMap>
@code{
public string[] Palette = new string[] {
"#C33764", "#AB3566", "#993367", "#853169",
"#742F6A", "#632D6C", "#532C6D", "#412A6F",
"#312870", "#1D2671"
};
}Startup.cs Configuration:
using Newtonsoft.Json.Serialization;
namespace BlazorApplication
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<OrderDataAccessLayer>();
// Add services for controllers
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
// Add endpoints for controller actions
endpoints.MapDefaultControllerRoute();
});
}
}
}Data Transformation Techniques
When working with complex data structures, transformation may be necessary to match TreeMap requirements.
Example: Flattening Nested Data
@code {
private List<FlattenedData> TransformHierarchicalData(List<HierarchicalData> source)
{
var result = new List<FlattenedData>();
foreach (var continent in source)
{
foreach (var country in continent.Countries)
{
result.Add(new FlattenedData
{
Continent = continent.Name,
Country = country.Name,
Population = country.Population
});
}
}
return result;
}
}Example: Aggregating Data
@code {
private List<AggregatedData> AggregateData(List<DetailedData> source)
{
return source
.GroupBy(x => x.Category)
.Select(g => new AggregatedData
{
Category = g.Key,
TotalValue = g.Sum(x => x.Value),
ItemCount = g.Count()
})
.ToList();
}
}Troubleshooting
Data Not Displaying
Problem: TreeMap renders but shows no data.
Solutions: 1. Verify WeightValuePath references a numeric property 2. Check that TValue matches your data type 3. Ensure DataSource is not null or empty 4. Confirm property names match exactly (case-sensitive)
@code {
// Add diagnostic output
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
Console.WriteLine($"Data Count: {GrowthReports?.Count ?? 0}");
Console.WriteLine($"First Item: {GrowthReports?.FirstOrDefault()?.Country}");
}
}
}Incorrect Item Sizes
Problem: TreeMap items have unexpected sizes.
Solutions: 1. Check for zero or negative values in WeightValuePath property 2. Verify numeric data types (use double/decimal for precision) 3. Consider data scale and normalization
Remote Data Not Loading
Problem: Remote data fails to load or displays errors.
Solutions: 1. Check CORS configuration on API 2. Verify API endpoint URL 3. Ensure correct Adaptor is used 4. Check network tab for HTTP errors 5. Validate response data format
@code {
// Add error handling
private string ErrorMessage { get; set; }
protected override async Task OnInitializedAsync()
{
try
{
// Your data loading code
}
catch (HttpRequestException ex)
{
ErrorMessage = $"Network error: {ex.Message}";
}
catch (Exception ex)
{
ErrorMessage = $"Error: {ex.Message}";
}
}
}Hierarchical Data Not Grouping
Problem: Hierarchical data displays flat without grouping.
Solutions: 1. Add TreeMapLevels configuration 2. Specify GroupPath for each level 3. Verify data structure matches expected hierarchy 4. Check collection property names
Performance Considerations
Large Datasets
For datasets with thousands of items:
1. Implement pagination for remote data 2. Use virtual scrolling if available 3. Consider data aggregation before binding 4. Limit initial display and provide drill-down
@code {
private const int MaxInitialItems = 100;
private List<GDPReport> GetOptimizedData()
{
return AllData
.OrderByDescending(x => x.GDP)
.Take(MaxInitialItems)
.ToList();
}
}Memory Management
1. Dispose of HttpClient properly 2. Clear unused data from memory 3. Use pagination for remote sources 4. Implement lazy loading for hierarchical data
Rendering Optimization
1. Avoid frequent data rebinding 2. Use `ShouldRender` to control updates 3. Batch data updates when possible 4. Cache transformed data
@code {
private List<GDPReport> _cachedData;
protected override bool ShouldRender()
{
// Control rendering based on data changes
return _dataChanged;
}
}Best Practices Summary
1. ✅ Use strongly-typed collections 2. ✅ Handle null/empty data gracefully 3. ✅ Implement loading indicators 4. ✅ Add error boundaries 5. ✅ Validate data before binding 6. ✅ Use appropriate adaptor for remote data 7. ✅ Consider performance for large datasets 8. ✅ Cache frequently accessed data 9. ✅ Test with various data sizes 10. ✅ Document data structure requirements
Drill Down
Table of Contents
Overview
Patterns for hierarchical navigation inside a TreeMap, including EnableDrillDown, DrillDownView, EnableBreadcrumb, BreadcrumbConnector, and TreeMapInitialDrillSettings.
Enabling Drill-Down
- Handle
OnDrillStartandDrillCompletedevents, or enable drill down directly on the TreeMap.
Breadcrumb Navigation
- Maintain breadcrumb state to allow users to navigate back through levels.
Custom Drill Paths
- Define custom paths or filters when the default grouping does not match UX needs.
Reset and State Management
- Provide a reset action to return to the root level and preserve selection state as required.
Events and Methods
Table of Contents
Overview
Lists the TreeMapEvents callbacks and the main SfTreeMap<TValue> methods.
Common Events
OnClick,OnDoubleClick,OnRightClick,OnItemClick,OnItemMove,ItemSelected, andItemHighlightedare exposed throughTreeMapEvents.
Render Events
Load,Loaded,ItemRendering,LegendRendering,LegendItemRendering,TooltipRendering, andResizingare available for render-time customization.
Methods: Print & Export
- Use
PrintAsync(),ExportAsync(), and the export-relatedAllowPrint,AllowPdfExport, andAllowImageExportproperties.
Utility Methods
- Use
RefreshAsync()andSelectItemAsync()for programmatic updates and selection.
Getting Started with TreeMap
Table of Contents
Overview
This reference explains how to add and render the Syncfusion Blazor TreeMap component in a Blazor application. It covers installation, project setup, and a minimal working example.
Prerequisites
- .NET SDK installed
- Blazor project (WASM or Server)
- Syncfusion Blazor packages available in NuGet
Install Package
Install the Syncfusion.Blazor.TreeMap NuGet package into your project and restore packages.
Minimal Example
@using Syncfusion.Blazor.TreeMap
<SfTreeMap WeightValuePath="EmployeeCount" TValue="Employee" DataSource="Employees" >
<TreeMapLevels>
<TreeMapLevel GroupPath="Country">
</TreeMapLevel>
</TreeMapLevels>
</SfTreeMap>
@code{
public class Employee
{
public string Country { get; set; }
public string JobDescription { get; set; }
public string JobGroup { get; set; }
public int EmployeeCount { get; set; }
};
public List<Employee> Employees = new List<Employee> {
new Employee { Country= "USA", JobDescription= "Sales", JobGroup= "Executive", EmployeeCount= 20 },
new Employee { Country= "USA", JobDescription= "Sales", JobGroup= "Analyst", EmployeeCount= 30 },
new Employee { Country= "USA", JobDescription= "Marketing", EmployeeCount= 40 },
new Employee { Country= "USA", JobDescription= "Management", EmployeeCount= 80 },
};
}Project Types
- Visual Studio, Visual Studio Code, and .NET CLI instructions are supported. Use the standard Blazor project templates.
Common Issues
- Missing NuGet package: run
dotnet add package Syncfusion.Blazor.TreeMap -v <version> - Rendering errors: ensure correct
DataSourceandGroupPathsettings.
Getting Started with Blazor TreeMap
A comprehensive guide for installing, configuring, and implementing the Syncfusion Blazor TreeMap component in your Blazor applications (WebAssembly, Server, and Web App).
Table of Contents
- Overview
- Prerequisites
- Installation Methods
- Blazor WebAssembly Application
- Blazor Web App
- Project Configuration
- Import Namespaces
- Register Syncfusion Services
- Add Script Resources
- Add Theme Stylesheets
- Your First TreeMap Component
- Adding Labels
- Adding Title
- Applying Color Mapping
- Enabling Legend
- Enabling Tooltip
- License Registration
- Troubleshooting Common Issues
Overview
The Syncfusion Blazor TreeMap component visualizes hierarchical data as nested rectangles, where rectangle size represents quantitative values and colors indicate additional dimensions. This guide covers installation and basic setup for all Blazor hosting models.
What You'll Learn:
- Installing the NuGet package across different development environments
- Configuring services and resources for Blazor WebAssembly, Server, and Web App
- Creating your first TreeMap with data binding
- Adding essential features (labels, title, color mapping, legend, tooltip)
Estimated Time: 15-20 minutes
Prerequisites
Before starting, ensure you have:
- Visual Studio 2022 (17.0 or later) OR Visual Studio Code with C# extension
- .NET SDK 6.0 or later - Check version with
dotnet --version - Basic Blazor knowledge - Understanding of components and data binding
- Syncfusion License - Free Community License or commercial license (required for production)
System Requirements:
- For detailed system requirements, visit: Blazor System Requirements
Installation Methods
Choose the installation method based on your Blazor hosting model and development environment.
Blazor WebAssembly Application
Using Visual Studio
Step 1: Create Blazor WebAssembly Project
1. Open Visual Studio 2022 2. Select File → New → Project 3. Search for "Blazor WebAssembly App" template 4. Configure project name and location 5. Click Create
Step 2: Install NuGet Package
Option A: NuGet Package Manager UI 1. Right-click project in Solution Explorer 2. Select Manage NuGet Packages 3. Click Browse tab 4. Search for Syncfusion.Blazor.TreeMap 5. Select latest version and click Install
Option B: Package Manager Console
Install-Package Syncfusion.Blazor.TreeMap -Version 27.1.48Replace 27.1.48 with the latest version available.
Using Visual Studio Code
Step 1: Create Blazor WebAssembly Project
Open integrated terminal (Ctrl+\`) and run:
dotnet new blazorwasm -o MyTreeMapApp
cd MyTreeMapAppStep 2: Install NuGet Package
dotnet add package Syncfusion.Blazor.TreeMap
dotnet restoreUsing .NET CLI (Command Line)
Step 1: Verify .NET SDK Installation
dotnet --versionExpected output: 8.0.x or higher
Step 2: Create Project
dotnet new blazorwasm -o MyTreeMapApp
cd MyTreeMapAppStep 3: Install Package
dotnet add package Syncfusion.Blazor.TreeMap
dotnet restoreBlazor Web App
Blazor Web App (introduced in .NET 8) supports multiple render modes. Installation varies based on interactivity settings.
Using Visual Studio
Step 1: Create Blazor Web App
1. Open Visual Studio 2022 2. Select File → New → Project 3. Search for "Blazor Web App" template 4. Configure project settings 5. Important: Select Interactive render mode (Auto, WebAssembly, or Server) 6. Select Interactivity location (Global or Per page/component) 7. Click Create

Step 2: Install NuGet Package
- For Server render mode: Install in the main server project only
- For WebAssembly or Auto mode: Install in BOTH server project AND
.Clientproject
Use NuGet Package Manager or Package Manager Console:
Install-Package Syncfusion.Blazor.TreeMap -Version 27.1.48Using Visual Studio Code
Step 1: Create Blazor Web App with Auto Render Mode
dotnet new blazor -o MyTreeMapApp -int Auto
cd MyTreeMapAppAvailable render mode options:
-int Server- Server-side rendering only-int WebAssembly- Client-side WebAssembly only-int Auto- Automatic switching between Server and WebAssembly
Step 2: Install NuGet Package
For WebAssembly or Auto mode, navigate to client project:
cd MyTreeMapApp.Client
dotnet add package Syncfusion.Blazor.TreeMap
dotnet restore
cd ..For Server mode, install in main project:
dotnet add package Syncfusion.Blazor.TreeMap
dotnet restoreUsing .NET CLI
Step 1: Create Project
dotnet new blazor -o MyTreeMapApp -int Auto
cd MyTreeMapAppStep 2: Install Package
For WebAssembly/Auto mode:
cd MyTreeMapApp.Client
dotnet add package Syncfusion.Blazor.TreeMap
dotnet restore
cd ..Project Configuration
After installing the NuGet package, configure your project to use Syncfusion components.
Import Namespaces
Open _Imports.razor file (root of project for WebAssembly, or in .Client project for Web App) and add:
@using Syncfusion.Blazor
@using Syncfusion.Blazor.TreeMapFile Location:
- WebAssembly:
~/Imports.razor - Web App (Auto/WebAssembly):
~/.Client/_Imports.razor - Web App (Server):
~/_Imports.razor
Register Syncfusion Services
Blazor WebAssembly
Open Program.cs and register services:
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Syncfusion.Blazor;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
// Register Syncfusion Blazor Service
builder.Services.AddSyncfusionBlazor();
await builder.Build().RunAsync();Blazor Web App
For Server or WebAssembly/Auto mode, register in BOTH files:
File 1: Main Project `Program.cs` (Server)
using Syncfusion.Blazor;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
// Register Syncfusion Blazor Service
builder.Services.AddSyncfusionBlazor();
var app = builder.Build();
// ... rest of configurationFile 2: Client Project `Program.cs` (for WebAssembly/Auto mode)
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Syncfusion.Blazor;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// Register Syncfusion Blazor Service
builder.Services.AddSyncfusionBlazor();
await builder.Build().RunAsync();Add Script Resources
Blazor WebAssembly
Add script reference in wwwroot/index.html inside <head> section:
<head>
<meta charset="utf-8" />
<title>My TreeMap App</title>
<base href="/" />
<link href="css/app.css" rel="stylesheet" />
<!-- Syncfusion Blazor Script -->
<script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js"
type="text/javascript"></script>
</head>Blazor Web App
Add script reference at the end of <body> in Components/App.razor:
<body>
<Routes />
<!-- Syncfusion Blazor Script -->
<script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js"
type="text/javascript"></script>
</body>Alternative: Individual script references for smaller bundle sizes - see Adding Script Reference.
Add Theme Stylesheets
Add CSS theme reference in <head> section:
Blazor WebAssembly
wwwroot/index.html:
<head>
<!-- Syncfusion Blazor Theme -->
<link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
</head>Blazor Web App
Components/App.razor:
<head>
<HeadOutlet />
<!-- Syncfusion Blazor Theme -->
<link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
</head>Available Themes:
bootstrap5.css- Bootstrap 5 (recommended)material3.css- Material Design 3fluent2.css- Fluent Design 2tailwind3.css- Tailwind CSS 3material.css- Material Design (classic)fabric.css- Microsoft Fabricbootstrap4.css- Bootstrap 4
Your First TreeMap Component
Now create your first TreeMap component with basic data binding.
Blazor WebAssembly
Open Pages/Index.razor and replace content with:
@page "/"
@using Syncfusion.Blazor.TreeMap
<PageTitle>TreeMap Demo</PageTitle>
<h1>GDP by Country - 2015</h1>
<SfTreeMap DataSource="@GrowthReport"
WeightValuePath="GDP"
TValue="Country">
</SfTreeMap>
@code {
public class Country
{
public string Name { get; set; }
public double GDP { get; set; }
}
public List<Country> GrowthReport = new List<Country>
{
new Country { Name = "United States", GDP = 17946 },
new Country { Name = "China", GDP = 10866 },
new Country { Name = "Japan", GDP = 4123 },
new Country { Name = "Germany", GDP = 3355 },
new Country { Name = "United Kingdom", GDP = 2848 },
new Country { Name = "France", GDP = 2421 },
new Country { Name = "India", GDP = 2073 },
new Country { Name = "Italy", GDP = 1814 },
new Country { Name = "Brazil", GDP = 1774 },
new Country { Name = "Canada", GDP = 1550 }
};
}Blazor Web App
For Web App, add render mode directive if interactivity location is "Per page/component":
Create `Pages/TreeMapDemo.razor`:
@page "/treemap-demo"
@rendermode InteractiveAuto
@using Syncfusion.Blazor.TreeMap
<PageTitle>TreeMap Demo</PageTitle>
<h1>GDP by Country - 2015</h1>
<SfTreeMap DataSource="@GrowthReport"
WeightValuePath="GDP"
TValue="Country">
</SfTreeMap>
@code {
public class Country
{
public string Name { get; set; }
public double GDP { get; set; }
}
public List<Country> GrowthReport = new List<Country>
{
new Country { Name = "United States", GDP = 17946 },
new Country { Name = "China", GDP = 10866 },
new Country { Name = "Japan", GDP = 4123 },
new Country { Name = "Germany", GDP = 3355 },
new Country { Name = "United Kingdom", GDP = 2848 },
new Country { Name = "France", GDP = 2421 },
new Country { Name = "India", GDP = 2073 },
new Country { Name = "Italy", GDP = 1814 },
new Country { Name = "Brazil", GDP = 1774 },
new Country { Name = "Canada", GDP = 1550 }
};
}Render Mode Options:
@rendermode InteractiveAuto- Automatic (recommended)@rendermode InteractiveWebAssembly- Client-side only@rendermode InteractiveServer- Server-side only- Omit directive if interactivity location is "Global"
Run the Application
Press Ctrl+F5 (Windows) or ⌘+F5 (macOS) to run without debugging.
Expected Output: TreeMap displaying 10 countries with rectangle sizes proportional to GDP values.
Adding Labels
Display text labels on TreeMap items by specifying the LabelPath property:
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@GrowthReport"
WeightValuePath="GDP"
TValue="Country">
<TreeMapLeafItemSettings LabelPath="Name" Fill="lightgray">
</TreeMapLeafItemSettings>
</SfTreeMap>Key Properties:
LabelPath="Name"- Property from data source to display as labelFill="lightgray"- Background color for leaf items
Result: Each rectangle now shows the country name.
Adding Title
Add a descriptive title using TreeMapTitleSettings:
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@GrowthReport"
WeightValuePath="GDP"
TValue="Country">
<TreeMapTitleSettings Text="Top 10 Countries by GDP Nominal - 2015">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="Name" Fill="lightgray">
</TreeMapLeafItemSettings>
</SfTreeMap>Customization Options:
@using Syncfusion.Blazor.TreeMap
<TreeMapTitleSettings Text="Top 10 Countries by GDP Nominal - 2015">
<TreeMapTitleTextStyle Size="18px"
FontWeight="Bold"
Color="#333333"
FontFamily="Arial">
</TreeMapTitleTextStyle>
<TreeMapSubtitleSettings Text="Source: World Bank 2015">
<TreeMapSubtitleTextStyle Size="12px" Color="#666666">
</TreeMapSubtitleTextStyle>
</TreeMapSubtitleSettings>
</TreeMapTitleSettings>Applying Color Mapping
Use color mapping to represent additional data dimensions through colors.
Range Color Mapping
Assign colors based on value ranges:
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@GrowthReport"
WeightValuePath="GDP"
RangeColorValuePath="GDP"
TValue="Country">
<TreeMapTitleSettings Text="Top 10 Countries by GDP Nominal - 2015">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping StartRange="0"
EndRange="3000"
Color="@(new string[] { "Orange" })">
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000"
EndRange="20000"
Color="@(new string[] { "Green" })">
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
</SfTreeMap>Key Properties:
RangeColorValuePath="GDP"- Property used for color calculationStartRange/EndRange- Value range for color applicationColor- Array of colors (single color or gradient)
Result: Countries with GDP < 3000 appear orange, >= 3000 appear green.
Enabling Legend
Add a legend to explain color mappings:
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@GrowthReport"
WeightValuePath="GDP"
RangeColorValuePath="GDP"
TValue="Country">
<TreeMapTitleSettings Text="Top 10 Countries by GDP Nominal - 2015">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping StartRange="0"
EndRange="3000"
Color="@(new string[] { "Orange" })"
Label="Low GDP">
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000"
EndRange="20000"
Color="@(new string[] { "Green" })"
Label="High GDP">
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
<TreeMapLegendSettings Visible="true" Position="Syncfusion.Blazor.TreeMap.LegendPosition.Top">
</TreeMapLegendSettings>
</SfTreeMap>Legend Customization:
@using Syncfusion.Blazor.TreeMap
<TreeMapLegendSettings Visible="true"
Position="Syncfusion.Blazor.TreeMap.LegendPosition.Top"
Mode="Syncfusion.Blazor.TreeMap.LegendMode.Default"
Height="50px"
Width="200px">
<TreeMapLegendTextStyle Size="14px" Color="#000000">
</TreeMapLegendTextStyle>
</TreeMapLegendSettings>Position Options: Top, Bottom, Left, Right
Enabling Tooltip
Display detailed information on hover:
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@GrowthReport"
WeightValuePath="GDP"
RangeColorValuePath="GDP"
TValue="Country">
<TreeMapTitleSettings Text="Top 10 Countries by GDP Nominal - 2015">
</TreeMapTitleSettings>
<TreeMapLeafItemSettings LabelPath="Name">
<TreeMapLeafColorMappings>
<TreeMapLeafColorMapping StartRange="0"
EndRange="3000"
Color="@(new string[] { "Orange" })">
</TreeMapLeafColorMapping>
<TreeMapLeafColorMapping StartRange="3000"
EndRange="20000"
Color="@(new string[] { "Green" })">
</TreeMapLeafColorMapping>
</TreeMapLeafColorMappings>
</TreeMapLeafItemSettings>
<TreeMapLegendSettings Visible="true">
</TreeMapLegendSettings>
<TreeMapTooltipSettings Visible="true" Format="${Name} : ${GDP} Billion">
</TreeMapTooltipSettings>
</SfTreeMap>Format Tokens:
${PropertyName}- Value from data source- Supports custom HTML/templates
Result: Hovering over a country shows "Country Name : GDP Value Billion"
License Registration
For production use, you must register a valid Syncfusion license key.
Obtain License Key
1. Community License (free): https://www.syncfusion.com/products/communitylicense 2. Commercial License: Available with purchase 3. Trial License: 30-day trial from Syncfusion website
Register License
In Program.cs, add license registration before builder.Build():
using Syncfusion.Blazor;
using Syncfusion.Licensing;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// ... other configuration
// Register Syncfusion License
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY");
builder.Services.AddSyncfusionBlazor();
await builder.Build().RunAsync();⚠️ Important:
- Replace
YOUR_LICENSE_KEYwith actual license key - Missing license shows warning banner in production
- License is not required for development/debugging
Troubleshooting Common Issues
Issue 1: TreeMap Not Rendering
Symptoms: Blank page or no TreeMap visible
Solutions: 1. Verify NuGet package installed: Check .csproj for <PackageReference Include="Syncfusion.Blazor.TreeMap" /> 2. Check service registration: Ensure AddSyncfusionBlazor() is called in Program.cs 3. Verify script reference: Check browser console for 404 errors on syncfusion-blazor.min.js 4. Confirm theme CSS: Inspect page source for Syncfusion theme link
Issue 2: "Type or namespace 'Syncfusion' could not be found"
Solution: Add namespace imports to _Imports.razor:
@using Syncfusion.Blazor
@using Syncfusion.Blazor.TreeMapIssue 3: Data Not Displaying
Symptoms: TreeMap renders but shows empty/no rectangles
Solutions: 1. Verify DataSource is not null or empty 2. Check WeightValuePath matches numeric property in data model 3. Ensure TValue matches data collection type 4. Confirm data property types (e.g., GDP must be numeric, not string)
Issue 4: Render Mode Errors (Blazor Web App)
Error: "Cannot provide a value for property 'RenderMode' on type..."
Solution: Add render mode directive for Per page/component interactivity:
@rendermode InteractiveAutoOr remove if interactivity location is Global.
Issue 5: Script Errors in Browser Console
Error: "Syncfusion is not defined"
Solution: Ensure script is loaded before component renders:
- WebAssembly: Script in
<head>ofindex.html - Web App: Script at end of
<body>inApp.razor - Check script path:
_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js
Issue 6: License Warning in Production
Warning Banner: "This application was built using a trial version..."
Solution: Register valid license key in Program.cs:
SyncfusionLicenseProvider.RegisterLicense("YOUR_LICENSE_KEY");Issue 7: Build Errors After Package Installation
Error: "The type or namespace name 'TreeMap' does not exist in the namespace 'Syncfusion.Blazor'"
Solutions: 1. Clean and rebuild solution:
dotnet clean
dotnet restore
dotnet build2. Restart IDE (Visual Studio/VS Code) 3. Check package version compatibility with .NET SDK version
Issue 8: Performance Issues with Large Datasets
Symptoms: Slow rendering or browser freeze
Solutions: 1. Limit initial data to 500-1000 items 2. Use hierarchical data with drill-down instead of flat data 3. Implement pagination or virtualization 4. Consider using Web App with Server render mode for better performance
Next Steps
Now that you have a working TreeMap, explore advanced features:
1. Data Binding - Connect to APIs, databases, and JSON files 2. Layout Customization - Experiment with Squarified, Horizontal, Vertical layouts 3. Multi-Level Hierarchies - Create drill-down navigation with TreeMapLevels 4. Advanced Color Mapping - Use Equal, Desaturation, and Palette mappings 5. Interactive Features - Add selection, highlight, and custom events 6. Export Capabilities - Enable PDF and image export
Refer to other reference files in this skill for comprehensive feature documentation.
Additional Resources
- Official Documentation: Syncfusion Blazor TreeMap Docs
- API Reference: TreeMap API Docs
- Live Demos: TreeMap Examples
- GitHub Samples: Blazor Getting Started Examples
- Support: Syncfusion Support Portal
Selection and Highlight
Table of Contents
Overview
How to configure TreeMapSelectionSettings and TreeMapHighlightSettings for TreeMap items. The TreeMapSelectionSettings class provides properties like Enable, Mode, Fill, and Opacity to manage item selection, while TreeMapHighlightSettings class provides the same properties to manage hover highlight behavior.
Selection Modes
- Use
Enableproperty to activate or deactivate selection functionality inTreeMapSelectionSettings. - Use
Modeproperty to specify the selection mode (SelectionMode.All, SelectionMode.Child, SelectionMode.Item, SelectionMode.Parent) inTreeMapSelectionSettings. - Use
Fillproperty to set the fill color of selected TreeMap items inTreeMapSelectionSettings. - Use
Opacityproperty to set the opacity level of selected TreeMap items inTreeMapSelectionSettings.
Highlight on Hover
- Use
Enableproperty to activate or deactivate highlight functionality on hover inTreeMapHighlightSettings. - Use
Modeproperty to specify the highlight mode (HighLightMode.All, HighLightMode.Child, HighLightMode.Item, HighLightMode.Parent) for hovered items inTreeMapHighlightSettings. - Use
Fillproperty to set the fill color of highlighted TreeMap items inTreeMapHighlightSettings. - Use
Opacityproperty to set the opacity level of highlighted TreeMap items inTreeMapHighlightSettings.
Programmatic Selection
- Use
SelectItemAsync()method onSfTreeMap<TValue>to programmatically select TreeMap items. - Use
SelectItemAsync()method with appropriate parameters (string[] levelOrder, bool isSelected = true) to clear or modify item selection state.
Combining with Drill-Down
- Use selection state from
TreeMapSelectionSettingsto persist user context across drill-down transitions. - Maintain selection context when navigating between drill-down levels in TreeMap.
Code Sample
Example 1: Enable Selection with Custom Fill Color
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@Data" TValue="DataModel" WeightValuePath="Weight" ColorValuePath="Color">
<TreeMapSelectionSettings Enable="true" Mode="SelectionMode.Item" Fill="#FF5733" Opacity="0.8"></TreeMapSelectionSettings>
<TreeMapLevels>
<TreeMapLevel GroupPath="Continent"></TreeMapLevel>
<TreeMapLevel GroupPath="Country"></TreeMapLevel>
</TreeMapLevels>
</SfTreeMap>
@code {
private List<DataModel> Data = new List<DataModel>
{
new DataModel { Continent = "Asia", Country = "India", Weight = 50, Color = "#FF5733" },
new DataModel { Continent = "Asia", Country = "China", Weight = 60, Color = "#33FF57" },
new DataModel { Continent = "Europe", Country = "Germany", Weight = 45, Color = "#3366FF" }
};
public class DataModel
{
public string Continent { get; set; }
public string Country { get; set; }
public int Weight { get; set; }
public string Color { get; set; }
}
}Example 2: Enable Highlight on Hover with Custom Fill Color
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@Data" TValue="DataModel" WeightValuePath="Weight" ColorValuePath="Color">
<TreeMapHighlightSettings Enable="true" Mode="HighLightMode.Item" Fill="#00FF00" Opacity="0.5"></TreeMapHighlightSettings>
<TreeMapLevels>
<TreeMapLevel GroupPath="Continent"></TreeMapLevel>
<TreeMapLevel GroupPath="Country"></TreeMapLevel>
</TreeMapLevels>
</SfTreeMap>
@code {
private List<DataModel> Data = new List<DataModel>
{
new DataModel { Continent = "Asia", Country = "India", Weight = 50, Color = "#FF5733" },
new DataModel { Continent = "Asia", Country = "China", Weight = 60, Color = "#33FF57" },
new DataModel { Continent = "Europe", Country = "Germany", Weight = 45, Color = "#3366FF" }
};
public class DataModel
{
public string Continent { get; set; }
public string Country { get; set; }
public int Weight { get; set; }
public string Color { get; set; }
}
}Example 3: Combining Selection and Highlight
@using Syncfusion.Blazor.TreeMap
<SfTreeMap DataSource="@Data" TValue="DataModel" WeightValuePath="Weight" ColorValuePath="Color">
<TreeMapSelectionSettings Enable="true" Mode="SelectionMode.Item" Fill="#FF5733" Opacity="0.8"></TreeMapSelectionSettings>
<TreeMapHighlightSettings Enable="true" Mode="HighLightMode.Item" Fill="#FFC300" Opacity="0.6"></TreeMapHighlightSettings>
<TreeMapLevels>
<TreeMapLevel GroupPath="Continent"></TreeMapLevel>
<TreeMapLevel GroupPath="Country"></TreeMapLevel>
</TreeMapLevels>
</SfTreeMap>
@code {
private List<DataModel> Data = new List<DataModel>
{
new DataModel { Continent = "Asia", Country = "India", Weight = 50, Color = "#FF5733" },
new DataModel { Continent = "Europe", Country = "Germany", Weight = 45, Color = "#33FF57" }
};
public class DataModel
{
public string Continent { get; set; }
public string Country { get; set; }
public int Weight { get; set; }
public string Color { get; set; }
}
}Troubleshooting
Table of Contents
Overview
Quick list of common problems and how to resolve them.
Rendering Problems
- Verify
DataSource,GroupPath, and layout settings. Ensure CSS does not hide elements.
Data Binding Issues
- Check for null/undefined values, inconsistent nesting, or incorrect
WeightValuePath.
Performance Issues
- Reduce item count, aggregate data, or use virtualized strategies; avoid expensive templates on thousands of items.
Common Fixes
- Restore default settings to verify behavior, log data shapes before binding, and progressively enable features to identify regressions.