跳過到頁腳內容
.NET幫助

C# ObservableCollection(對開發者來說是如何工作的)

在 C# 中,ObservableCollection 是一種強大的資料結構,當項目添加、移除或更改時,它會自動通知監聽者。 它特別適用於動態數據收集場景,例如當您需要在 UI 或報告中反映即時變化時。 結合 IronPDF,可以使用此強大的集合生成基於實時數據的動態 PDF。

IronPDF 是一個用於在 C# 中生成 PDF 的強大庫。 憑藉其 HTML 到 PDF 的轉換功能,不論是需要生成發票、報告或基於即時數據的任何其他文件都很容易生成高品質的 PDF。 在本文中,我們將向您展示如何將 ObservableCollection 類與 IronPDF 集成,利用數據綁定來生成 PDF,隨著數據的變化動態更新。

理解 ObservableCollection

什麼是 ObservableCollection?

ObservableCollection 是 C# 中的一個類,它實現了 INotifyCollectionChanged 接口,提供了在添加、移除或修改項目時的通知。 它常用於像 WPF 這樣的 UI 應用程序中的數據綁定,集合的更改會自動觸發 UI 的更新。 與其他集合如 List 不同,ObservableCollection 提供內置的事件通知,使其非常適合需要實時反映數據的情況。

ObservableCollection 自動處理整個集合的變更,使得在應用程序中管理和顯示動態數據收集變得容易。

常见用例

  • 與 UI 組件綁定:例如在 WPF 中,ObservableCollection 常用於將數據綁定到控制項上,如 ListView、DataGrid 和 ComboBox。 當基礎集合發生變更時,UI 會自動更新。
  • 實時更新:當數據經常變更時,ObservableCollection 確保 UI 總是保持同步。 例如,可用於實時報告中,集合中新增數據條目,報告會相應更新。
  • 動態變更:如果您的應用允許用戶添加、刪除或修改數據,ObservableCollection 可以用來自動反映這些變化於 UI 或其他組件中。

使用 IronPDF

IronPDF 概覽

C# ObservableCollection(開發者如何使用):圖 1

就像我們在本文開頭提到的,IronPDF 是一個 .NET PDF 生成庫,讓創建、修改和渲染 PDF 文檔變得容易。 與某些其他 PDF 庫不同,IronPDF 提供了一套豐富的功能集來簡化與 PDF 的工作流程,例如將 HTML 轉換為 PDF、添加水印、操作現有的 PDF 等。

IronPDF 也允許開發者從不同的數據來源渲染 PDF,包括 HTML、圖片和純文本,這在需要呈現動態數據時特別有用。 使用 IronPDF 的 API,您可以生成高品質 PDF,包括詳細的佈局、表格、圖片和樣式。

IronPDF 設置

要開始使用 IronPDF,您需要通過 NuGet 安裝庫。 您可以運行以下命令在包管理控制台中將其添加到您的項目中:

Install-Package IronPdf

安裝後,您可以初始化 IronPDF 並使用其強大功能。 在本文中,我們將專注於從 ObservableCollection 中的動態數據生成 PDF。

將 ObservableCollection 與 IronPDF 集成

使用案例:從 ObservableCollection 動態生成 PDF

讓我們設想一個場景,您需要從一個存儲在 ObservableCollection 中的項目列表生成發票 PDF。 當項目從集合中添加或移除時,PDF 應自動重新生成以反映數據的當前狀態。

對於此任務,ObservableCollection 提供了一種簡單的方式來管理發票中的項目,而 IronPDF 將允許我們生成並導出該發票到 PDF 格式。

將數據綁定到 PDF 內容

要將 ObservableCollection 中的數據綁定到 PDF,您需要遍歷集合並將其項目添加到 PDF 內容中。 IronPDF 提供了創建表格、添加文本和自定義佈局的方法,使得可以以結構化的格式表示數據。

例如,如果您有一個包含多個項目的發票,您可以通過遍歷 ObservableCollection 並將每個項目添加到文檔中的表格或列表來動態生成 PDF。 IronPDF 提供高水平的自定義,包括調整字體、邊框,甚至可以包括如徽標或條形碼的圖片。

範例一:使用 ObservableCollection 生成 PDF

讓我們看一個簡單的範例來展示它如何工作。 假設您有一個人員集合(由 Person 類表示),並且您想生成一個反映這些人員詳細信息的 PDF。 每次有新的人物被加入到集合中,PDF 都會自動更新。

人物類範例

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

在這種情況下,Person 類包含基本屬性如 Name 和 Age。 我們將使用此類結合 ObservableCollection 動態生成 PDF。

創建 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

這個 ObservableCollection 包含了一個個 Person 對象的集合,每個對象都有一個 Name 和 Age。 當一個項目被添加或移除時,事件處理程序會被觸發,我們將用來動態更新 PDF。

為集合變更添加事件處理程序

在本例中,我們訂閱了 ObservableCollection 類 的 CollectionChanged 事件,以便每當集合變更時自動重新生成 PDF。 這在您需要響應更改(如添加或刪除 Person 對象)時非常有用。

// 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

向集合中添加新人物

您可以向集合中添加新的 Person,而 整個集合 將觸發事件處理程序以重新生成 PDF。 此方法自動處理對 整個人員列表 的更改。

// 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

每次您向集合中添加 新的人 時,PDF 會重新生成,包括新的條目。

綁定年齡屬性

您還可以將 Person 的 年齡 屬性綁定到某些外部系統(例如 UI 或應用程序的其他部分)以自動反映更改。

這裡是一個在 Person 類 中綁定 Age 屬性的範例:

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

使用 ObservableCollection 與綁定

讓我們演示如何將 綁定年齡 到 UI 元素,更新年齡值並觀察變化被反映在集合中:

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

使用 IronPDF 生成 PDF

現在我們已設置好 ObservableCollection 並添加事件處理程序,是時候專注於生成反映動態人員集合的 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");
}
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

範例二:從 ObservableCollection 生成 PDF 發票

以下是一個範例如何使用 IronPDF 從一個發票項目 ObservableCollection 生成 PDF:

步驟 1:示例發票項目類別

這個類表示發票中的一項,具有項目名稱、數量、價格和總價格的屬性。

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

步驟 2:示例 ObservableCollection

本範例初始化了一個包含數個發票項目的 ObservableCollection。 您可以動態添加、移除或修改此集合中的項目。

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

步驟 3:使用 IronPDF 生成 PDF

在這裡,我們創建一個函數用來生成 PDF。 此函數使用 ObservableCollection 中的數據並將其轉換為 HTML 然後使用 IronPDF 將其渲染為 PDF。

public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer 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 ChromePdfRenderer 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 ChromePdfRenderer 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

步驟 4:訂閱 CollectionChanged 事件

由於 ObservableCollection 自動通知變更,您可以輕鬆的每次集合更新時重新生成 PDF。 例如,如果一個項目被添加或移除,PDF 可以用更新的數據重新生成。

下面是如何訂閱 CollectionChanged 事件並且每當集合變更時重新生成 PDF:

// 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

步驟 5:添加項目和測試

您可以現在測試向 ObservableCollection 中添加新項目並觀察 PDF 如何自動重新生成。

// 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

完整程式碼範例

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 ChromePdfRenderer 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 ChromePdfRenderer 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);
    }
}
Imports System
Imports System.Collections.ObjectModel
Imports IronPdf

Public Class InvoiceItem
	Public Property ItemName() As String
	Public Property Quantity() As Integer
	Public Property Price() As Decimal
	' Property to calculate the total price for each item
	Public ReadOnly Property Total() As Decimal
		Get
			Return Quantity * Price
		End Get
	End Property
End Class
Public Class InvoiceGenerator
	' Function to generate the invoice PDF
	Public Sub GenerateInvoicePDF(ByVal items As ObservableCollection(Of InvoiceItem))
		Dim pdf = New ChromePdfRenderer() ' Initialize IronPDF's ChromePdfRenderer 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

	' Main function to test the code
	Public Shared Sub Main(ByVal args() As String)
		Dim invoiceItems = 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
			}
		}

'INSTANT VB NOTE: The variable invoiceGenerator was renamed since it may cause conflicts with calls to static members of the user-defined type with this name:
		Dim invoiceGenerator_Conflict As New InvoiceGenerator()

		' Subscribe to the ObservableCollection's CollectionChanged event
		AddHandler invoiceItems.CollectionChanged, Sub(sender, e)
			' Regenerate the PDF whenever the collection changes
			invoiceGenerator_Conflict.GenerateInvoicePDF(invoiceItems)
		End Sub

		' Generate initial PDF
		invoiceGenerator_Conflict.GenerateInvoicePDF(invoiceItems)

		' Add a new item to the collection and automatically regenerate the PDF
		invoiceItems.Add(New InvoiceItem With {
			.ItemName = "Item 4",
			.Quantity = 3,
			.Price = 12.50D
		})

		' Remove an item and see the PDF update
		invoiceItems.RemoveAt(0)
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

C# ObservableCollection(開發者如何使用):圖 2 - 輸出 PDF 文件

程式碼的功能

  • InvoiceItem 類:表示一個發票項目,具有 ItemName、Quantity、Price 和一個計算的 Total 屬性。
  • ObservableCollection:用來存儲發票項目列表。 集合自動通知監聽者任何更改(例如,當項目被添加或移除時)。
  • GenerateInvoicePDF:這個方法生成表示發票的 HTML 內容並使用 IronPDF 將其轉換為 PDF。
  • CollectionChanged:ObservableCollection 事件通過處理生成動態 PDF 每當集合更改時。
  • 測試:Main 方法演示如何從 ObservableCollection 添加和移除項目觸發 PDF 重新生成。

性能考量

處理大型集合

在處理大型 ObservableCollection 實例時,性能可能成為一個問題。 如果有大量項目,每次集合更改重新生成 PDF 可能會消耗資源。 為了減輕這種情況,考慮批量更新或使用分頁技術來避免過載 PDF 生成過程。

高效的 PDF 渲染

為確保 PDF 渲染效率高,請記住以下技巧:

  • 最小化不必要的重渲染:僅在數據發生重大更改(例如,當項目被添加或移除時)時重新生成 PDF。
  • 優化表格佈局:在渲染大型數據集時,將其分解為較小、更易於管理的部分以提高渲染時間。
  • 使用緩存:緩存先前生成的靜態或不頻繁更改的數據的 PDF。

結論

通過將 C# 的 ObservableCollection 與 IronPDF 結合,您可以輕鬆生成反映應用程序數據實時變化的動態 PDF。 無論您是在生成發票、報告或其他文件,這種方法允許您每當基礎集合變更時自動更新 PDF 內容。

ObservableCollection 的集成確保您的應用程序總是最新的,且需付出最小的努力,而 IronPDF 負責渲染高質量 PDF 的艱苦工作。 透過遵循本文討論的最佳實踐和性能技巧,您可以為您的 .NET 應用程序創建無縫的 PDF 生成體驗。

想親自嘗試 IronPDF 嗎? Download the free trial today to elevate your C# PDF projects, and be sure to check out the extensive documentation section to see more of this library in action.

常見問題解答

什麼是C#中的ObservableCollection?

ObservableCollection是C#中的一個類,實現了INotifyCollectionChanged接口。它提供了在添加、移除或修改項目時的通知,這使其非常適合在需要實時更新的UI應用程序中進行數據綁定。

如何在C#中從動態數據中生成PDF?

使用IronPDF,你可以通過利用C#的ObservableCollection從動態數據中生成PDF。隨著集合的更新,可以自動重新生成PDF以反映當前的數據狀態。

使用ObservableCollection與PDF生成有哪些好處?

ObservableCollection允許實時跟踪數據,這在生成需要反映動態數據變化的PDF時非常有用。結合IronPDF,確保數據中的任何更新都能及時反映在PDF輸出中。

如何將ObservableCollection中的數據綁定到C#中的PDF?

可以通過遍歷集合項並使用IronPDF的方法將它們添加到PDF中作為結構化元素(如表或列表)來將ObservableCollection中的數據綁定到PDF。這確保了PDF內容始終與數據保持同步。

在C#中使用ObservableCollection生成PDF的常見案例是什麼?

一個常見的案例是從ObservableCollection的項目生成發票。隨著項目的添加或移除,PDF發票可以重新生成,以準確反映當前的項目列表,確保文檔的及時性。

IronPDF如何處理C#中的HTML到PDF轉換?

IronPDF可以使用諸如RenderHtmlAsPdfRenderHtmlFileAsPdf等方法將HTML轉換為PDF。這使開發人員能夠從網頁或HTML字符串創建PDF,方便動態內容渲染。

在使用大型ObservableCollections進行PDF生成時應考慮什麼?

在處理大型集合時,應考慮使用分頁、批量更新和優化佈局以防止性能問題。IronPDF的緩存和渲染優化也有助於有效管理大數據。

IronPDF如何提高.NET應用程序的生產力?

IronPDF通過提供強大的PDF創建功能提高生產力,如詳細的佈局自定義、HTML到PDF轉換和與各種數據源的集成。它簡化了複雜的PDF任務,使開發人員能夠專注於核心應用程序邏輯。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。