Data Binding in Blazor
Data binding is a core concept in Blazor that simplifies synchronizing data between your UI components and your C# code. It allows you to display data from your application's state in the UI and update the application's state when the user interacts with the UI.
Types of Data Binding
Blazor supports several types of data binding:
- One-way binding: Updates the UI when the data changes.
- Two-way binding: Updates the UI when the data changes, and updates the data when the UI changes.
- Event binding: Handles user interactions and updates the application's state.
One-Way Binding
One-way binding is achieved using the @
symbol followed by the data property. When the data property changes, the UI automatically updates to reflect the new value.
Example: Displaying a User's Name
<p>Hello, @UserName!</p>
@code {
private string UserName { get; set; } = "Blazor User";
}
Two-Way Binding
Two-way binding is the most common and powerful form of data binding in Blazor. It's typically used with form elements like input fields. Blazor uses the @(
)
syntax for two-way binding, often in conjunction with the bind-value
attribute for input elements.
Example: Two-Way Binding with an Input Field
<input type="text" @bind-value="ProductName" />
<p>Product Name: @ProductName</p>
@code {
private string ProductName { get; set; } = "Default Product";
}
In this example, typing in the input field will immediately update the ProductName
property, and any changes to ProductName
in the code will update the input field.
Event Binding
Event binding allows you to respond to user actions like button clicks or input changes. This is done using the @onclick
, @onchange
, and other event attributes.
Example: Handling a Button Click
<button @onclick="IncrementCount">Click Me</button>
<p>Current Count: @currentCount</p>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Combining Binding Types
You can combine these binding types to create dynamic and interactive UI elements. For instance, you can use two-way binding for input fields and event binding to trigger an action when a specific value is entered.
Important Note on Performance
While Blazor's data binding is highly efficient, it's good practice to be mindful of frequent UI updates in performance-critical scenarios. Consider debouncing or throttling updates if you encounter performance issues with very complex or rapidly changing data.