AYUDA .NET

C# ObservableCollection (Cómo funciona para desarrolladores)

Introducción

En C#, la ObservableCollectiones una estructura de datos poderosa que notifica automáticamente a los oyentes cuando se agregan, eliminan o cambian elementos. Es particularmente útil para escenarios de recolección de datos dinámica, como cuando necesitas reflejar cambios en tiempo real en tu interfaz de usuario o informes. Cuando se combina con IronPDF, esta poderosa colección se puede utilizar para generar PDFs dinámicos basados en datos en vivo.

IronPDF es una biblioteca robusta para generar PDFs en C#. Con sus capacidades de conversión de HTML-a-PDF, es fácil crear PDFs de alta calidad, ya sea que necesite generar facturas, informes u otros documentos basados en datos en tiempo real. En este artículo, te mostraremos cómo integrar la clase ObservableCollection con IronPDF, aprovechando la vinculación de datos para generar un PDF que se actualiza dinámicamente a medida que los datos cambian.

Comprendiendo ObservableCollection

¿Qué es un ObservableCollection?

La clase ObservableCollectionen C# implementa la interfaz INotifyCollectionChanged, que proporciona notificaciones cuando se agregan, eliminan o modifican elementos. Se utiliza comúnmente para el enlace de datos en aplicaciones de interfaz de usuario como WPF, donde los cambios en la colección desencadenan automáticamente actualizaciones en la interfaz de usuario. A diferencia de otras colecciones como List, una ObservableCollection ofrece notificaciones de eventos integradas, lo que la hace perfecta para escenarios donde los datos necesitan reflejarse en tiempo real.

La ObservableCollection maneja automáticamente los cambios en toda la colección, lo que facilita la gestión y visualización de una colección de datos dinámica en su aplicación.

Casos de uso común

  • Vinculación con componentes de la interfaz de usuario: En WPF, por ejemplo, ObservableCollection se usa a menudo para vincular datos a controles como ListView, DataGrid y ComboBox. Cuando la colección subyacente cambia, la interfaz de usuario se actualiza automáticamente.
  • Actualizaciones en tiempo real: Cuando los datos cambian con frecuencia, ObservableCollection asegura que la interfaz de usuario siempre esté sincronizada. Por ejemplo, podrías usarlo para un informe en vivo donde se agreguen nuevas entradas de datos a la colección en tiempo real y el informe se actualice en consecuencia.
  • Cambios dinámicos: Si su aplicación permite a los usuarios agregar, eliminar o modificar datos, se puede utilizar ObservableCollection para reflejar automáticamente esos cambios en la interfaz de usuario u otros componentes.

Trabajando con IronPDF

Visión general de IronPDF

C# ObservableCollection (Cómo Funciona para Desarrolladores): Figura 1

Añadir desde PixabaySubir

o arrastre y suelte una imagen aquí

Agregar texto alternativo de la imagen

Como mencionamos al comienzo de este artículo, IronPDF es una biblioteca de generación de PDF para .NET que facilita la creación, modificación y renderización de documentos PDF. A diferencia de algunas otras bibliotecas de PDF, IronPDF ofrece un conjunto completo de funciones que simplifican el trabajo con PDFs, como la conversión de HTML a PDF, la adición de marcas de agua, la manipulación de PDFs existentes y más.

IronPDF también permite a los desarrolladores renderizar PDFs a partir de diferentes fuentes de datos, incluyendo HTML, imágenes y texto plano, lo cual puede ser especialmente útil cuando necesitas presentar datos dinámicos. Con la API de IronPDF, puedes generar PDFs de alta calidad, incluyendo diseños detallados, tablas, imágenes y estilos.

Configuración de IronPDF

Para comenzar con IronPDF, necesitas instalar la biblioteca a través de NuGet. Puede agregarlo a su proyecto ejecutando el siguiente comando en la Consola del Administrador de Paquetes:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
$vbLabelText   $csharpLabel

Una vez instalado, puedes inicializar IronPDF y utilizar sus potentes características. En este artículo, nos enfocaremos en generar PDFs a partir de datos dinámicos en un ObservableCollection.

Integración de ObservableCollection con IronPDF

Caso de Uso: Generación Dinámica de PDFs desde ObservableCollection

Imaginemos un escenario en el que necesitas generar un PDF de factura a partir de una lista de artículos almacenados en un ObservableCollection. A medida que se agregan o eliminan elementos de la colección, el PDF debe regenerarse automáticamente para reflejar el estado actual de los datos.

Para esta tarea, ObservableCollection proporciona una forma fácil de gestionar los elementos en la factura, mientras que IronPDF nos permitirá generar y exportar la factura a un formato PDF.

Vinculación de datos al contenido PDF

Para vincular los datos en un ObservableCollection a un PDF, necesitas recorrer la colección y agregar sus elementos al contenido del PDF. IronPDF proporciona métodos para crear tablas, agregar texto y personalizar el diseño, lo que facilita la representación de los datos en un formato estructurado.

Por ejemplo, si tiene una factura con varios artículos, puede generar dinámicamente el PDF recorriendo el ObservableCollection y agregando cada artículo a una tabla o lista en el documento. IronPDF permite un alto nivel de personalización, incluyendo el ajuste de fuentes, bordes e incluso la inclusión de imágenes como logotipos o códigos de barras.

Ejemplo Uno: Generar un PDF usando ObservableCollection

Veamos un ejemplo sencillo para demostrar cómo funciona esto. Supongamos que tienes una colección de personas (representadas por la clase Persona), y deseas generar un PDF que refleje los detalles de estas personas. Cada vez que se añada una nueva persona a la colección, el PDF se actualizará automáticamente.

Ejemplo de Clase Persona

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Public Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class
$vbLabelText   $csharpLabel

En este caso, la clase Person contiene propiedades básicas como Nombre y Edad. Usaremos esta clase junto con ObservableCollection para generar dinámicamente un PDF.

Creando el ObservableCollection

using System.Collections.ObjectModel;
var collection = new ObservableCollection<Person>
{
    new Person { Name = "John Doe", Age = 30 },
    new Person { Name = "Jane Smith", Age = 28 }
};
using System.Collections.ObjectModel;
var collection = new ObservableCollection<Person>
{
    new Person { Name = "John Doe", Age = 30 },
    new Person { Name = "Jane Smith", Age = 28 }
};
Imports System.Collections.ObjectModel
Private collection = New ObservableCollection(Of Person) From {
	New Person With {
		.Name = "John Doe",
		.Age = 30
	},
	New Person With {
		.Name = "Jane Smith",
		.Age = 28
	}
}
$vbLabelText   $csharpLabel

Esta ObservableCollection contiene una colección de objetos Person, cada uno con un Nombre y una Edad. Cuando se añade o elimina un elemento, se activan los controladores de eventos, que utilizaremos para actualizar el PDF dinámicamente.

Agregar controladores de eventos para cambios en la colección

En este ejemplo, nos suscribimos al evento CollectionChanged de la clase ObservableCollection para regenerar automáticamente el PDF cada vez que la colección cambie. Esto es útil si necesita responder a cambios como agregar o eliminar un objeto Persona.

// Subscribe to the ObservableCollection's CollectionChanged event
collection.CollectionChanged += (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) =>
{
    // Regenerate the PDF whenever the collection changes
    GeneratePersonPDF(collection);
};
// Subscribe to the ObservableCollection's CollectionChanged event
collection.CollectionChanged += (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) =>
{
    // Regenerate the PDF whenever the collection changes
    GeneratePersonPDF(collection);
};
' Subscribe to the ObservableCollection's CollectionChanged event
AddHandler collection.CollectionChanged, Sub(sender As Object, e As System.Collections.Specialized.NotifyCollectionChangedEventArgs)
	' Regenerate the PDF whenever the collection changes
	GeneratePersonPDF(collection)
End Sub
$vbLabelText   $csharpLabel

Añadiendo nuevas personas a la colección

Puedes agregar una nueva persona a la colección, y la colección completa activará el controlador de eventos para regenerar el PDF. Este enfoque maneja automáticamente los cambios en la lista completa de personas.

// Adding a new person to the collection
collection.Add(new Person { Name = "Alice Brown", Age = 32 });
// Adding a new person to the collection
collection.Add(new Person { Name = "Alice Brown", Age = 32 });
' Adding a new person to the collection
collection.Add(New Person With {
	.Name = "Alice Brown",
	.Age = 32
})
$vbLabelText   $csharpLabel

Cada vez que agregue una nueva persona a la colección, el PDF se regenerará, incluyendo la nueva entrada.

Propiedad de Edición Age

También puedes vincular la propiedad age de una Persona a algún sistema externo (como la interfaz de usuario u otras partes de la aplicación) para reflejar automáticamente los cambios.

Aquí tienes un ejemplo de cómo se vincularía la propiedad Age en la clase Person:

public class Person
{
    public string Name { get; set; }
    private int _age;
    public int Age 
    {
        get { return _age; }
        set
        {
            _age = value;
            // Raise property changed event here if using data binding
        }
    }
}
public class Person
{
    public string Name { get; set; }
    private int _age;
    public int Age 
    {
        get { return _age; }
        set
        {
            _age = value;
            // Raise property changed event here if using data binding
        }
    }
}
Public Class Person
	Public Property Name() As String
	Private _age As Integer
	Public Property Age() As Integer
		Get
			Return _age
		End Get
		Set(ByVal value As Integer)
			_age = value
			' Raise property changed event here if using data binding
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

Uso de ObservableCollection con Binding

Demostremos el uso de binding age a un elemento de la interfaz de usuario, actualizando el valor de la edad y observando cómo se reflejan los cambios en la colección:

ObservableCollection<Person> people = new ObservableCollection<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 28 }
};
// Binding the Age of the first person to a UI element (pseudo-code)
someUIElement.Text = people[0].Age.ToString();
ObservableCollection<Person> people = new ObservableCollection<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 28 }
};
// Binding the Age of the first person to a UI element (pseudo-code)
someUIElement.Text = people[0].Age.ToString();
Dim people As New ObservableCollection(Of Person) From {
	New Person With {
		.Name = "John",
		.Age = 30
	},
	New Person With {
		.Name = "Jane",
		.Age = 28
	}
}
' Binding the Age of the first person to a UI element (pseudo-code)
someUIElement.Text = people(0).Age.ToString()
$vbLabelText   $csharpLabel

Generando el PDF con IronPDF

Ahora que hemos configurado el ObservableCollection y agregado controladores de eventos, es hora de centrarnos en generar un PDF que refleje la colección dinámica de personas.

using IronPdf;
public void GeneratePersonPDF(ObservableCollection<Person> people)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
    // Create HTML content representing the people in the collection
    var htmlContent = "<h1>People Information</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Name</th><th>Age</th></tr>";
    foreach (var person in people)
    {
        htmlContent += $"<tr><td>{person.Name}</td><td>{person.Age}</td></tr>";
    }
    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("PeopleInformation.pdf");
}
using IronPdf;
public void GeneratePersonPDF(ObservableCollection<Person> people)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
    // Create HTML content representing the people in the collection
    var htmlContent = "<h1>People Information</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Name</th><th>Age</th></tr>";
    foreach (var person in people)
    {
        htmlContent += $"<tr><td>{person.Name}</td><td>{person.Age}</td></tr>";
    }
    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("PeopleInformation.pdf");
}
Imports IronPdf
Public Sub GeneratePersonPDF(ByVal people As ObservableCollection(Of Person))
	Dim pdf = New ChromePdfRenderer() ' Initialize IronPDF's ChromePdfRenderer class
	' Create HTML content representing the people in the collection
	Dim htmlContent = "<h1>People Information</h1><table border='1' cellpadding='5' cellspacing='0'>" & "<tr><th>Name</th><th>Age</th></tr>"
	For Each person In people
		htmlContent &= $"<tr><td>{person.Name}</td><td>{person.Age}</td></tr>"
	Next person
	htmlContent &= "</table>"
	' Convert the HTML content to a PDF
	Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
	' Save the generated PDF to disk
	pdfDocument.SaveAs("PeopleInformation.pdf")
End Sub
$vbLabelText   $csharpLabel

Ejemplo Dos: Generación de una factura PDF desde ObservableCollection

Aquí tienes un ejemplo de cómo generar un PDF a partir de una ObservableCollection de elementos de factura utilizando IronPDF:

Paso 1: Clase de Ejemplo de Elemento de Factura

Esta clase representa un artículo en la factura, con propiedades para el nombre del artículo, cantidad, precio y precio total.

public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public decimal Total => Quantity * Price;
}
public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public decimal Total => Quantity * Price;
}
Public Class InvoiceItem
	Public Property ItemName() As String
	Public Property Quantity() As Integer
	Public Property Price() As Decimal
	Public ReadOnly Property Total() As Decimal
		Get
			Return Quantity * Price
		End Get
	End Property
End Class
$vbLabelText   $csharpLabel

Paso 2: Muestra de ObservableCollection

Este ejemplo inicializa un ObservableCollection que contiene varios elementos de factura. Puede agregar, eliminar o modificar dinámicamente los elementos en esta colección.

ObservableCollection<InvoiceItem> invoiceItems = new ObservableCollection<InvoiceItem>
{
    new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
    new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
    new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
};
ObservableCollection<InvoiceItem> invoiceItems = new ObservableCollection<InvoiceItem>
{
    new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
    new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
    new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
};
Dim invoiceItems As New ObservableCollection(Of InvoiceItem) From {
	New InvoiceItem With {
		.ItemName = "Item 1",
		.Quantity = 2,
		.Price = 10.00D
	},
	New InvoiceItem With {
		.ItemName = "Item 2",
		.Quantity = 1,
		.Price = 25.00D
	},
	New InvoiceItem With {
		.ItemName = "Item 3",
		.Quantity = 5,
		.Price = 5.00D
	}
}
$vbLabelText   $csharpLabel

Paso 3: Generación del PDF con IronPDF

Aquí, creamos una función para generar el PDF. Esta función utiliza los datos en la ObservableCollection y los convierte en HTML, que luego se representa como un PDF usando IronPDF.

public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's HtmlToPdf class
    // Create HTML content representing the invoice
    var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
    foreach (var item in items)
    {
        htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
    }
    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("Invoice.pdf");
}
public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's HtmlToPdf class
    // Create HTML content representing the invoice
    var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
    foreach (var item in items)
    {
        htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
    }
    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("Invoice.pdf");
}
Public Sub GenerateInvoicePDF(ByVal items As ObservableCollection(Of InvoiceItem))
	Dim pdf = New ChromePdfRenderer() ' Initialize IronPDF's HtmlToPdf class
	' Create HTML content representing the invoice
	Dim htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" & "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>"
	For Each item In items
		htmlContent &= $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>"
	Next item
	htmlContent &= "</table>"
	' Convert the HTML content to a PDF
	Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
	' Save the generated PDF to disk
	pdfDocument.SaveAs("Invoice.pdf")
End Sub
$vbLabelText   $csharpLabel

Paso 4: Suscribirse al evento CollectionChanged

Debido a que ObservableCollection notifica automáticamente los cambios, puedes regenerar fácilmente el PDF cada vez que se actualice la colección. Por ejemplo, si se añade o elimina un artículo, se puede regenerar el PDF con los datos actualizados.

A continuación, se muestra cómo puede suscribirse al evento CollectionChanged y regenerar el PDF cada vez que la colección cambie:

// Subscribe to the ObservableCollection's CollectionChanged event
invoiceItems.CollectionChanged += (sender, e) =>
{
    // Regenerate the PDF whenever the collection changes
    GenerateInvoicePDF(invoiceItems);
};
// Subscribe to the ObservableCollection's CollectionChanged event
invoiceItems.CollectionChanged += (sender, e) =>
{
    // Regenerate the PDF whenever the collection changes
    GenerateInvoicePDF(invoiceItems);
};
' Subscribe to the ObservableCollection's CollectionChanged event
AddHandler invoiceItems.CollectionChanged, Sub(sender, e)
	' Regenerate the PDF whenever the collection changes
	GenerateInvoicePDF(invoiceItems)
End Sub
$vbLabelText   $csharpLabel

Paso 5: Añadir elementos y probar

Ahora puede probar añadiendo nuevos elementos a la ObservableCollection y observando cómo el PDF se regenera automáticamente.

// Adding a new item to the ObservableCollection
invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });
// Adding a new item to the ObservableCollection
invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });
' Adding a new item to the ObservableCollection
invoiceItems.Add(New InvoiceItem With {
	.ItemName = "Item 4",
	.Quantity = 3,
	.Price = 12.50D
})
$vbLabelText   $csharpLabel

Ejemplo de código completo

using System;
using System.Collections.ObjectModel;
using IronPdf;
public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    // Property to calculate the total price for each item
    public decimal Total => Quantity * Price;
}
public class InvoiceGenerator
{
    // Function to generate the invoice PDF
    public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
    {
        var pdf = new ChromePdfRenderer();  // Initialize IronPDF's HtmlToPdf class
        // Create HTML content representing the invoice
        var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                          "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
        foreach (var item in items)
        {
            htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
        }
        htmlContent += "</table>";
        // Convert the HTML content to a PDF
        var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
        // Save the generated PDF to disk
        pdfDocument.SaveAs("Invoice.pdf");
    }
    // Main function to test the code
    public static void Main(string[] args)
    {
        var invoiceItems = new ObservableCollection<InvoiceItem>
        {
            new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
            new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
            new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
        };
        var invoiceGenerator = new InvoiceGenerator();
        // Subscribe to the ObservableCollection's CollectionChanged event
        invoiceItems.CollectionChanged += (sender, e) =>
        {
            // Regenerate the PDF whenever the collection changes
            invoiceGenerator.GenerateInvoicePDF(invoiceItems);
        };
        // Generate initial PDF
        invoiceGenerator.GenerateInvoicePDF(invoiceItems);
        // Add a new item to the collection and automatically regenerate the PDF
        invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });
        // Remove an item and see the PDF update
        invoiceItems.RemoveAt(0);
    }
}
using System;
using System.Collections.ObjectModel;
using IronPdf;
public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    // Property to calculate the total price for each item
    public decimal Total => Quantity * Price;
}
public class InvoiceGenerator
{
    // Function to generate the invoice PDF
    public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
    {
        var pdf = new ChromePdfRenderer();  // Initialize IronPDF's HtmlToPdf class
        // Create HTML content representing the invoice
        var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                          "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
        foreach (var item in items)
        {
            htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
        }
        htmlContent += "</table>";
        // Convert the HTML content to a PDF
        var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
        // Save the generated PDF to disk
        pdfDocument.SaveAs("Invoice.pdf");
    }
    // Main function to test the code
    public static void Main(string[] args)
    {
        var invoiceItems = new ObservableCollection<InvoiceItem>
        {
            new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
            new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
            new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
        };
        var invoiceGenerator = new InvoiceGenerator();
        // Subscribe to the ObservableCollection's CollectionChanged event
        invoiceItems.CollectionChanged += (sender, e) =>
        {
            // Regenerate the PDF whenever the collection changes
            invoiceGenerator.GenerateInvoicePDF(invoiceItems);
        };
        // Generate initial PDF
        invoiceGenerator.GenerateInvoicePDF(invoiceItems);
        // Add a new item to the collection and automatically regenerate the PDF
        invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });
        // Remove an item and see the PDF update
        invoiceItems.RemoveAt(0);
    }
}
CONVERTER NOT RUNNING
$vbLabelText   $csharpLabel

Salida

C# ObservableCollection (Cómo funciona para desarrolladores): Figura 2 - Archivo PDF de salida

Añadir desde PixabaySubir

o arrastre y suelte una imagen aquí

Texto alternativo claro

Lo que hace el código

  • Clase InvoiceItem: Representa un elemento de factura con propiedades para ItemName, Quantity, Price y un Total calculado.
  • ObservableCollection: Se utiliza para almacenar la lista de elementos de la factura. La colección notifica automáticamente a los oyentes sobre cualquier cambio (por ejemplo, cuando se añaden o eliminan elementos).
  • GenerateInvoicePDF: Este método crea el contenido HTML que representa la factura y utiliza IronPDF para convertirlo a PDF.
  • CollectionChanged: Se maneja el evento ObservableCollection para regenerar el PDF cada vez que la colección cambia, haciendo que la generación de PDF sea dinámica.
  • Pruebas: El método Main demuestra cómo la adición y eliminación de elementos de la ObservableCollection activa la regeneración del PDF.

Consideraciones sobre el rendimiento

Manejo de grandes colecciones

Cuando se trabaja con grandes instancias de ObservableCollection, el rendimiento puede convertirse en una preocupación. Regenerar un PDF cada vez que la colección cambia puede ser intensivo en recursos si hay un gran número de elementos. Para mitigar esto, considere agrupar las actualizaciones o utilizar técnicas como la paginación para evitar sobrecargar el proceso de generación de PDF.

Renderizado eficiente de PDF

Para garantizar que la renderización de PDF sea eficiente, tenga en cuenta los siguientes consejos:

  • Minimizar renders innecesarios: Solo regenerar el PDF cuando los datos cambien significativamente (por ejemplo, cuando se añadan o eliminen elementos).
  • Optimizar la disposición de la tabla: Al renderizar grandes conjuntos de datos, divídelos en secciones más pequeñas y manejables para mejorar el tiempo de renderizado.
  • Usar caché: Almacenar en caché los PDF previamente generados para datos estáticos o que cambian con poca frecuencia.

Conclusión

Al combinar ObservableCollection de C# con IronPDF, puedes generar fácilmente PDFs dinámicos que reflejen cambios en tiempo real en los datos de tu aplicación. Ya sea que esté generando facturas, informes u otros documentos, este enfoque le permite actualizar automáticamente el contenido del PDF cada vez que la colección subyacente cambie.

La integración de ObservableCollection garantiza que su aplicación esté siempre actualizada con un esfuerzo mínimo, mientras que IronPDF se encarga del trabajo pesado de renderizar PDFs de alta calidad. Al seguir las mejores prácticas y los consejos de rendimiento discutidos en este artículo, puedes crear una experiencia de generación de PDF fluida para tus aplicaciones .NET.

¿Quieres probar IronPDF tú mismo? Descargue la documentación extensa para ver más de esta biblioteca en acción.

Chipego
Ingeniero de software
Chipego tiene una habilidad natural para escuchar que le ayuda a comprender los problemas de los clientes y a ofrecer soluciones inteligentes. Se unió al equipo de Iron Software en 2023, después de estudiar una licenciatura en Tecnología de la Información. IronPDF e IronOCR son los dos productos en los que Chipego se ha centrado, pero su conocimiento de todos los productos crece día a día, a medida que encuentra nuevas formas de ayudar a los clientes. Disfruta de lo colaborativa que es la vida en Iron Software, con miembros del equipo de toda la empresa que aportan su variada experiencia para contribuir a soluciones eficaces e innovadoras. Cuando Chipego está lejos de su escritorio, a menudo se le puede encontrar disfrutando de un buen libro o jugando al fútbol.
SIGUIENTE >
C# XOR (Cómo funciona para desarrolladores)