Tenga en cuenta que este control ha quedado obsoleto y reemplazado por Grid y, como tal, recomendamos migrar a ese control. Esto no recibirá ninguna característica nueva, las correcciones de errores no tendrán prioridad. Para obtener ayuda o preguntas sobre la migración de su código base a Data Grid, comuníquese con el soporte.
Descripción general de la cuadrícula de datos Blazor
La Ignite UI for Blazor es un componente de cuadrícula tabular Blazor que le permite vincular y mostrar rápidamente sus datos con poca codificación o configuración. Las características de la cuadrícula de datos Blazor incluyen filtrado, ordenamiento, plantillas, selección de filas, agrupación de filas, fijación de filas y columnas movibles. Las tablas Blazor están optimizadas para datos en vivo y en tiempo real, con la capacidad de manejar un tamaño de conjunto de datos ilimitado en cantidad de filas o columnas.
Esta demostración implementa algunas de las funciones que están disponibles en la cuadrícula: filtrado, agrupación, fijar/desanclar columnas, reposicionar columnas, ordenar y resúmenes.
EXAMPLE
MODULES
DATA GENERATOR
DATA SOURCE
RAZOR
JS
CSS
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using IgniteUI.Blazor.Controls; // for registering Ignite UI modulesnamespaceInfragistics.Samples
{
publicclassProgram
{
publicstaticasync Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// registering Ignite UI modules
builder.Services.AddIgniteUIBlazor(
typeof(IgbDataGridModule),
typeof(IgbDataGridToolbarModule),
typeof(IgbGridColumnOptionsModule),
typeof(IgbSparklineModule)
);
await builder.Build().RunAsync();
}
}
}cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespaceInfragistics.Samples
{
publicclassEmployee : INotifyPropertyChanged
{
publicstring ID { get; set; }
publicstring Address { get; set; }
publicdouble Age { get; set; }
publicstring Gender { get; set; }
publicstring FirstName { get; set; }
publicstring LastName { get; set; }
publicstring Name { get; set; }
publicstring Street { get; set; }
publicstring City { get; set; }
publicstring Email { get; set; }
publicstring Phone { get; set; }
publicstring Photo { get; set; }
publicdouble Salary { get; set; }
publicdouble Sales { get; set; }
publicstring Income { get; set; }
publicint Index { get; set; }
public DateTime Birthday { get; set; }
public List<Productivity> Productivity { get; set; }
privatestring _Country;
publicstring Country
{
get { return _Country; }
set { if (_Country != value) { OnCountryChanged(value); } }
}
publicstring CountryFlag { get; set; }
protectedvoidOnCountryChanged(string countryName)
{
// syncronizing country name and country flag
_Country = countryName;
CountryFlag = DataGenerator.GetCountryFlag(countryName);
City = DataGenerator.GetCity(countryName);
OnPropertyChanged("Country");
}
publicevent PropertyChangedEventHandler PropertyChanged;
protectedvirtualvoidOnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
publicclassProductivity
{
publicdouble Value { get; set; }
publicint Week { get; set; }
}
publicstaticclassEmployeeData
{
publicstatic List<Employee> Create(int? count, bool? useProductivity)
{
if (count == null) count = 100;
var employees = new List<Employee>();
for (int i = 0; i < count; i++)
{
var age = Math.Round(DataGenerator.GetNumber(20, 40));
var gender = DataGenerator.GetGender();
var firstName = DataGenerator.GetNameFirst(gender);
var lastName = DataGenerator.GetNameLast();
var street = DataGenerator.GetStreet();
var country = DataGenerator.GetCountry();
var city = DataGenerator.GetCity(country);
var email = firstName.ToLower() + "@" + DataGenerator.GetEmail();
var photoPath = DataGenerator.GetPhoto(gender);
var employee = new Employee
{
Index = i,
Address = street + ", " + city,
Age = age,
Birthday = DataGenerator.GetBirthday(),
City = city,
Email = email,
Gender = gender,
ID = DataGenerator.Pad(1001 + i, 4),
FirstName = firstName,
LastName = lastName,
Name = firstName + " " + lastName,
Photo = photoPath,
Phone = DataGenerator.GetPhone(),
Street = DataGenerator.GetStreet(),
Salary = DataGenerator.GetNumber(40, 200) * 1000,
Sales = DataGenerator.GetNumber(200, 980) * 1000,
};
employee.Country = country;
employee.Income = DataGenerator.GetIncomeRange(employee.Salary);
if (useProductivity.HasValue && useProductivity.Value)
{
employee.Productivity = GetProductivity(52);
}
employees.Add(employee);
}
return employees;
}
publicstatic List<Productivity> GetProductivity(int weekCount)
{
var productivity = new List<Productivity>();
for (var w = 1; w <= weekCount; w++)
{
varvalue = DataGenerator.GetNumber(-50, 50);
var prod = new Productivity
{
Value = value,
Week = w
};
productivity.Add(prod);
};
return productivity;
}
}
}cs
@using Microsoft.AspNetCore.Components@using Microsoft.AspNetCore.Components.Rendering@using Microsoft.AspNetCore.Components.Forms@using Microsoft.AspNetCore.Components.RenderTree@using Microsoft.AspNetCore.Components.Web
@using IgniteUI.Blazor.Controls<divclass="container vertical"><divclass="container vertical">@if (Employees != null)
{<IgbDataGridToolbarToolbarTitle="Sales Team"ColumnChooser="true"ColumnPinning="true"TargetGrid="@DataGridRef"/><divstyle="overflow: hidden"><IgbDataGridHeight="100%"Width="100%"
@ref="@DataGridRef"RowHeight="50"DataSource="Employees"AutoGenerateColumns="false"IsColumnOptionsEnabled="true"IsGroupCollapsable="true"ActivationMode="GridActivationMode.Cell"SummaryScope="@SummaryScope.Root"GroupSummaryDisplayMode="@GroupSummaryDisplayMode.RowBottom"GroupHeaderDisplayMode="@GroupHeaderDisplayMode.Combined"CornerRadiusTopLeft="0"CornerRadiusTopRight="0"ColumnMovingSeparatorWidth="2"ColumnMovingMode="ColumnMovingMode.Deferred"ColumnMovingAnimationMode="ColumnMovingAnimationMode.SlideOver"ColumnShowingAnimationMode="ColumnShowingAnimationMode.SlideFromRightAndFadeIn"ColumnHidingAnimationMode="ColumnHidingAnimationMode.SlideToRightAndFadeOut"SelectionMode="DataGridSelectionMode.SingleRow"><IgbImageColumnIsEditable="false"Width="@("*>120")"Field="Photo"PaddingTop="5"PaddingBottom="5"PaddingRight="10"HorizontalAlignment="@CellContentHorizontalAlignment.Stretch" /><IgbTextColumnWidth="@("*>130")"Field="Name" />@*NOTE: CellUpdatingScript is implemented in wwwroot/*.js file *@<IgbTemplateColumnWidth="@("*>160")"Field="Sales"CellUpdatingScript="onUpdatingSalesColumn"HorizontalAlignment="@CellContentHorizontalAlignment.Center" /><IgbNumericColumnWidth="@("*>130")"Field="Salary"PositivePrefix="$"ShowGroupingSeparator="true"MaxFractionDigits="0"MinFractionDigits="0" /><IgbNumericColumnWidth="100"Field="Age"HorizontalAlignment="@CellContentHorizontalAlignment.Center"/><IgbDateTimeColumnWidth="@("*>140")"Field="Birthday"HeaderText="Date of Birth" /><IgbImageColumnIsEditable="false"Width="@("*>110")"Field="CountryFlag"HeaderText="Country"PaddingTop="5"PaddingBottom="5"PaddingRight="10"HorizontalAlignment="@CellContentHorizontalAlignment.Stretch" />@*NOTE: CellUpdatingScript is implemented in wwwroot/*.js file *@<IgbTemplateColumnWidth="@("*>170")"Field="Address"CellUpdatingScript="onUpdatingAddressColumn" /><IgbTemplateColumnWidth="@("*>130")"Field="Phone"CellUpdatingScript="onUpdatingPhoneColumn" /><IgbTextColumnWidth="@("*>120")"Field="Income" /><IgbTextColumnWidth="@("*>120")"Field="Email"IsEditable="false" /></IgbDataGrid></div>}</div></div>@code {private List<Employee> Employees;
private IgbDataGrid _grid;
private IgbDataGrid DataGridRef
{
get { return _grid; }
set { _grid = value; this.OnDataGridRef(); StateHasChanged(); }
}
protectedoverridevoidOnInitialized()
{
this.Employees = EmployeeData.Create(100, false);
}
privatevoidOnDataGridRef()
{
var peopleGroup = new IgbColumnGroupDescription() { Field = "Country", DisplayName = "Country" };
var incomeGroup = new IgbColumnGroupDescription() { Field = "Income", DisplayName = "Income" };
this._grid.GroupDescriptions.Add(peopleGroup);
this._grid.GroupDescriptions.Add(incomeGroup);
var ageSummary = new IgbColumnSummaryDescription() { Field = "Age", Operand = DataSourceSummaryOperand.Average };
var peopleSummary = new IgbColumnSummaryDescription() { Field = "Photo", Operand = DataSourceSummaryOperand.Count };
var salarySummary = new IgbColumnSummaryDescription() { Field = "Salary", Operand = DataSourceSummaryOperand.Sum };
var saleSummary = new IgbColumnSummaryDescription() { Field = "Sales", Operand = DataSourceSummaryOperand.Max };
this._grid.SummaryDescriptions.Add(ageSummary);
this._grid.SummaryDescriptions.Add(peopleSummary);
this._grid.SummaryDescriptions.Add(salarySummary);
this._grid.SummaryDescriptions.Add(saleSummary);
// TODO fix onSummarziePeopleGender//var nameSummary = new IgbColumnSummaryDescription() { Field = "Name", Operand = DataSourceSummaryOperand.Custom,// ProvideCalculatorScript = "onSummarziePeopleGender" };//this._grid.SummaryDescriptions.Add(nameSummary);
}
}razor
// NOTE this JavaScript file implements functions for styling/templating columnd of the DataGrid control// at end of this file, the igRegisterScript registers functions that are used .razor filefunctiononUpdatingSalesColumn(grid, args) {
let content = args.content;
let info = args.cellInfo;
let sales = info.rowItem.Sales;
let gaugeValue = null;
let gaugeBar = null;
if (content.childElementCount === 0) {
gaugeValue = document.createElement("span");
gaugeValue.style.margin = "0px";
gaugeValue.style.marginTop = "2px";
gaugeValue.style.padding = "0px";
gaugeValue.style.fontFamily = "Verdana";
gaugeValue.style.fontSize = "13px";
gaugeValue.style.textAlign = "center";
gaugeBar = document.createElement("div");
gaugeBar.style.background = "#7f7f7f";
gaugeBar.style.padding = "0px";
gaugeBar.style.margin = "0px";
gaugeBar.style.height = "6px";
gaugeBar.style.left = "0px";
gaugeBar.style.top = "0px";
gaugeBar.style.position = "relative";
const gauge = document.createElement("div");
gauge.style.background = "#dddddd";
gauge.style.padding = "0px";
gauge.style.margin = "0px";
gauge.style.height = "4px";
gauge.style.marginTop = "8px";
gauge.style.width = "100%";
gauge.appendChild(gaugeBar);
content.style.verticalAlign = "center";
content.style.lineHeight = "normal";
content.style.display = "flex";
content.style.flexDirection = "column";
content.style.justifyContent = "center";
content.style.height = "100%";
content.style.width = "calc(100% - 2rem)";
content.style.marginRight = "1rem";
content.style.marginLeft = "1rem";
content.appendChild(gauge);
content.appendChild(gaugeValue);
} else {
const gauge = content.children[0];
gaugeBar = gauge.children[0];
gaugeValue = content.children[1];
}
// conditional formatting:if (sales < 400000) {
gaugeValue.style.color = "rgb(211, 17, 3)";
gaugeBar.style.background = "rgb(211, 17, 3)";
}
elseif (sales < 650000) {
gaugeValue.style.color = "Orange";
gaugeBar.style.background = "Orange";
}
else {
gaugeValue.style.color = "rgb(21, 190, 6)";
gaugeBar.style.background = "rgb(21, 190, 6)";
}
let gaugeWidth = (sales / 990000) * 100;
gaugeWidth = Math.min(100, gaugeWidth);
gaugeBar.style.width = gaugeWidth + "%";
gaugeValue.textContent = "$" + sales / 1000 + ",000";
}
functiononUpdatingAddressColumn(grid, args) {
let content = args.content;
let info = args.cellInfo;
let item = info.rowItem;
let span1 = null;
let span2 = null;
if (content.childElementCount === 0) {
content.style.fontFamily = "Verdana";
content.style.fontSize = "13px";
content.style.verticalAlign = "center";
content.style.lineHeight = "normal";
content.style.display = "flex";
content.style.flexDirection = "column";
content.style.justifyContent = "center";
content.style.height = "100%";
content.style.width = "100%";
content.style.color = "rgb(24, 29, 31)";
// stacking above elements in the content of grid's cell
span1 = document.createElement("span");
span2 = document.createElement("span");
content.appendChild(span1);
content.appendChild(span2);
}
else {
span1 = content.children[0];
span2 = content.children[1];
}
if (span1 && span2) {
// updating elements in the content of grid's cell
span1.textContent = item.Street;
span2.textContent = item.City + ", " + item.Country;
}
}
functiononUpdatingPhoneColumn(grid, args) {
let content = args.content;
let info = args.cellInfo;
let item = info.rowItem;
let link = null;
if (content.childElementCount === 0) {
link = document.createElement("a");
content.style.verticalAlign = "center";
content.style.justifyContent = "center";
content.style.lineHeight = "normal";
content.style.display = "inline-block";
// content.style.display = "inline-grid";
content.style.fontFamily = "Verdana";
content.style.fontSize = "13px";
content.style.color = "#4286f4";
content.style.width = "100%";
content.appendChild(link);
} else {
link = content.children[0];
}
link.href = "tel:" + item.Phone;
link.textContent = item.Phone;
}
// this code allows calling above functions from a .razor file
igRegisterScript("onUpdatingSalesColumn", onUpdatingSalesColumn, false);
igRegisterScript("onUpdatingAddressColumn", onUpdatingAddressColumn, false);
igRegisterScript("onUpdatingPhoneColumn", onUpdatingPhoneColumn, false);
functiononSummarziePeopleGender(grid, args) {
//TODO//let info = args.cellInfo;//let gender = info.rowItem.Gender;
args.setCalculator(10);
}
igRegisterScript("onSummarziePeopleGender", onSummarziePeopleGender, false);
js
/*
CSS styles are loaded from the shared CSS file located at:
https://static.infragistics.com/xplatform/css/samples/
*/css
¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Blazor completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.
Empezando
dependencias
Consulte estos temas sobre cómo agregar el paquete IgniteUI.Blazor.
// in Program.cs file
builder.Services.AddIgniteUIBlazor(typeof(IgbDataGridModule));
razor
Módulos opcionales
Las características opcionales IgbGrid, vistas arriba, requieren los siguientes módulos:
// in Program.cs file
builder.Services.AddIgniteUIBlazor(
typeof(IgbDataGridModule),
typeof(IgbDataGridToolbarModule),
typeof(IgbSparklineModule)
);
razor
Fuente de datos de muestra
Ahora que se ha importado el módulo de cuadrícula de datos Blazor, el siguiente paso es la configuración básica de la cuadrícula Blazor que se vincula a los datos locales.
@code {public List<SaleInfo> DataSource { get; set;}
Random Rand = new Random();
protectedoverridevoidOnInitialized()
{
GenerateData();
}
publicvoidGenerateData()
{
string[] names = newstring[] {
"Intel CPU", "AMD CPU",
"Intel Motherboard", "AMD Motherboard", "Nvidia Motherboard",
"Nvidia GPU", "Gigabyte GPU", "Asus GPU", "AMD GPU", "MSI GPU",
"Corsair Memory", "Patriot Memory", "Skill Memory",
"Samsung HDD", "WD HDD", "Seagate HDD", "Intel HDD", "Asus HDD",
"Samsung SSD", "WD SSD", "Seagate SSD", "Intel SSD", "Asus SSD",
"Samsung Monitor", "Asus Monitor", "LG Monitor", "HP Monitor" };
string[] countries = newstring[] {
"USA", "UK", "France", "Canada", "Poland",
"Denmark", "Croatia", "Australia", "Seychelles",
"Sweden", "Germany", "Japan", "Ireland",
"Barbados", "Jamaica", "Cuba", "Spain", };
string[] status = newstring[] { "Packing", "Shipped", "Delivered" };
var sales = new List<SaleInfo>();
for (var i = 0; i < 200; i++)
{
var price = GetRandomNumber(10000, 90000) / 100;
var items = GetRandomNumber(4, 30);
varvalue = Math.Round(price * items);
var margin = GetRandomNumber(2, 5);
var profit = Math.Round((price * margin / 100) * items);
var country = GetRandomItem(countries);
var item = new SaleInfo()
{
Country = country,
CountryFlag = GetCountryFlag(country),
Margin = margin,
OrderDate = GetRandomDate(),
OrderItems = items,
OrderValue = value,
ProductID = 1001 + i,
ProductName = GetRandomItem(names),
ProductPrice = price,
Profit = Math.Round(profit),
Status = GetRandomItem(status)
};
sales.Add(item);
}
this.DataSource = sales;
}
publicdoubleGetRandomNumber(double min, double max)
{
return Math.Round(min + (Rand.NextDouble() * (max - min)));
}
publicstringGetRandomItem(string[] array)
{
var index = (int)Math.Round(GetRandomNumber(0, array.Length - 1));
return array[index];
}
public DateTime GetRandomDate() {
var today = new DateTime();
var year = today.Year;
var month = this.GetRandomNumber(1, 9);
var day = this.GetRandomNumber(10, 27);
returnnew DateTime(year, (int)month, (int)day);
}
publicstringGetCountryFlag(string country)
{
var flag = "https://static.infragistics.com/xplatform/images/flags/" + country + ".png";
return flag;
}
publicclassSaleInfo
{
publicstring? Status { get; set; }
publicstring? ProductName { get; set; }
publicstring? CountryFlag { get; set; }
publicstring? Country { get; set; }
public DateTime OrderDate { get; set; }
publicdouble Profit { get; set; }
publicdouble ProductPrice { get; set; }
publicdouble ProductID { get; set; }
publicdouble OrderValue { get; set; }
publicdouble OrderItems { get; set; }
publicdouble Margin { get; set; }
}
}razor
Generar columnas automáticamente
El siguiente código demuestra cómo vincular la cuadrícula de datos Blazor a los datos locales anteriores.