How to drag and drop of listbox element into blazor diagram control?
Here’s a comprehensive guide to implementing drag-and-drop functionality to transfer items from a ListBox component into a Diagram in a Blazor application. This example explains the necessary setup, event handling, and JavaScript interop to achieve smooth drag-and-drop behavior with accurate positioning.
Overview
This example allows users to drag items from a ListBox and drop them onto a Diagram canvas. Each item dropped is transformed into a node in the Diagram with the item’s content displayed as an annotation.
Implementation Steps
Follow these steps to set up and configure the ListBox and Diagram components, handle the drag-and-drop events, and manage precise positioning using JavaScript interop.
Step 1: Set Up the Razor Page Layout
Add the following markup to a Razor page to create the layout, which includes a ListBox for draggable items and a Diagram component as the drop target.
@page "/"
@using Syncfusion.Blazor.DropDowns
@using Syncfusion.Blazor.Diagram
@inject IJSRuntime jsRuntime;
<div class="source content-container position-relative">
<div class="row">
<!-- ListBox Section -->
<div class="col-md-3" id="listbox" style="padding-left: 2rem;">
<h4>Connectors</h4>
<SfListBox @ref="ListBoxObj" DataSource="@filteredData" Scope="Diagram" TItem="ExtractorUI" AllowDragAndDrop="true" TValue="string[]">
<ListBoxFieldSettings Text="Extractor" Value="yamlfile" />
<ListBoxEvents TValue="string[]" TItem="ExtractorUI" DragStart="DragStart" OnDrop="OnDrop" />
</SfListBox>
</div>
<!-- Diagram Section -->
<div class="col-md-9" style="padding-left:1rem;">
<SfDiagramComponent ID="Diagram" @ref="Diagram" Height="700px"></SfDiagramComponent>
</div>
</div>
</div>
- ListBox Section: Displays draggable items. The Scope is set to “Diagram,” allowing items to be dropped only onto the Diagram component.
- Diagram Section: Serves as the target where ListBox items are dropped. Each dropped item appears as a node with an annotation.
Step 2: Define Code-Behind for Data Binding and Event Handling
- Initialize Data: Load sample data for ListBox items.
- Handle Drag and Drop Events: Implement DragStart and OnDrop to manage drag-and-drop operations.
In the @code section of the Razor file:
@code {
public SfDiagramComponent Diagram;
SfListBox<string[], ExtractorUI> ListBoxObj;
private List<ExtractorUI> filteredData = new List<ExtractorUI>();
private string sampleData = "[{\"Extractor\":\"Facebook Ads\",\"yamlfile\":\"version: 1\"},...]"; // Sample JSON data
protected override async Task OnInitializedAsync()
{
// Deserialize sample data into ListBox items
filteredData = JsonSerializer.Deserialize<List<ExtractorUI>>(sampleData);
}
bool isDragging;
// Sets dragging state when drag begins
public void DragStart(DragEventArgs<ExtractorUI> args)
{
isDragging = true;
}
// Handles drop event to add ListBox items as nodes in the Diagram
public async void OnDrop(DropEventArgs<ExtractorUI> args)
{
ExtractorUI item = args.Items.First<ExtractorUI>();
if (isDragging)
{
// Fetch ListBox width to adjust positioning
string listViewWith = await jsRuntime.InvokeAsync<string>("getlistViewWidth", "listbox");
double listViewWithDoubleValue = Double.Parse(listViewWith);
// Add a new node to Diagram based on ListBox item details
await Diagram.AddDiagramElements(new DiagramObjectCollection<NodeBase>()
{
new Node()
{
Height = 100,
Width = 100,
OffsetX = args.Left-listViewWithDoubleValue,
OffsetY = args.Top,
Annotations = new DiagramObjectCollection<ShapeAnnotation>()
{
new ShapeAnnotation()
{
Content = filteredData[args.DropIndex].Extractor,
}
}
}
});
isDragging = false;
}
currentPosition = null;
}
}
Explanation of Code:
- Data Initialization: Deserialize JSON data into a ListBox data source, filteredData.
- DragStart Event: Sets the isDragging flag, which triggers when an item is dragged from the ListBox.
- OnDrop Event: Converts the dropped ListBox item into a Diagram node. The position of the node is adjusted based on ListBox width using JavaScript interop.
Step 3: Implement JavaScript Interop for Accurate Positioning
To position dropped items correctly in the Diagram, use JavaScript to get the ListBox width. This ensures the node’s position in the Diagram aligns with the cursor’s drop location.
Add the following JavaScript function in wwwroot/index.html (or the layout file):
// JavaScript function to get the ListBox width
function getlistViewWidth(id){
var idw = document.getElementById(id);
return idw.offsetWidth.toString();
}
Step 4: Define Supporting Classes
Define ExtractorUI to represent each ListBox item’s data model:
public class ExtractorUI
{
public string Extractor { get; set; }
public string yamlfile { get; set; }
public bool IsEdited { get; set; }
public bool IsCustom { get; set; }
}
Step 5: Configure ListBox for Drag-and-Drop
In the SfListBox component:
- Set AllowDragAndDrop=“true” to enable dragging.
- Set Scope=“Diagram” to define the Diagram as the drop target.
ListBox Events - DragStart: Triggers when dragging begins, setting the isDragging flag.
- OnDrop: Handles the item drop, adding a node to the Diagram with the relevant ListBox item’s information.
Step 6: Verify Drag-and-Drop Functionality
- Run the application.
- Drag an item from the ListBox and drop it onto the Diagram. The item should appear as a node in the Diagram, with its content displayed as an annotation.
Output:
You can download the complete working sample from here.
Conclusion:
You can refer to our Blazor Diagram feature tour page to learn about its other groundbreaking features, documentation, and how to quickly get started with configuration specifications. You can also explore our Blazor Diagram example to understand how to create and manipulate diagram elements.
For current customers, our Blazor components are available on the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to evaluate our Blazor Diagram and other Blazor components.
If you have any questions or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac,, or feedback portal. We are always happy to assist you!