跳過到頁腳內容
.NET幫助

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

在C#中,ObservableCollection是強大的資料結構,自動在加入、移除或更改項目時通知監聽者。 它特別適合動態資料收集情境,例如當您需要在用戶界面或報告中反映實時變化時。 結合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都會自動更新。

Person類範例

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; }
}
$vbLabelText   $csharpLabel

在這個例子中,Person類包含基本屬性,如姓名和年齡。 我們將使用這個類結合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 }
};
$vbLabelText   $csharpLabel

這個ObservableCollection包含一個人員物件集合,每個物件都有名稱和年齡。 當項目被新增或移除時,事件處理程式會被觸發,我們將用它來動態更新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);
};
$vbLabelText   $csharpLabel

向集合中新增新人

您可以向集合中新增一個新的人,整個集合將觸發事件處理程式以重新生成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 });
$vbLabelText   $csharpLabel

每次您將新人新增到集合中,PDF將會重新生成,包括這個新條目。

繫結年齡屬性

您還可以將Person的年齡屬性繫結到某個外部系統(例如UI或應用程式的其他部分)以自動反映變化。

以下是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
        }
    }
}
$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();
$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");
}
$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;
}
$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 }
};
$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");
}
$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);
};
$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 });
$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);
    }
}
$vbLabelText   $csharpLabel

輸出

C# ObservableCollection(對於開發者的作用):圖2 - 輸出PDF文件

代碼的作用

  • InvoiceItem類: 代表一個發票項,擁有ItemName、Quantity、Price和一個計算的Total屬性。
  • ObservableCollection: 用於存儲發票項的列表。 集合自動通知監聽者任何更改(例如,當項被新增或移除時)。
  • GenerateInvoicePDF: 此方法創建代表發票的HTML內容,並使用IronPDF將其轉換為PDF。
  • CollectionChanged: 使用ObservableCollection事件來處理每次集合變更時的PDF重新生成,使PDF生成變得動態。
  • 測試: Main方法展示了如何在新增和刪除ObservableCollection中的項目時觸發PDF重生。

效能考量

處理大型集合

當處理大型ObservableCollection實例時,效能可能會成為一個問題。 如果有大量項,每次集合更改都重新生成PDF可能資源密集。 為了減輕這一問題,考慮批量更新或使用分頁等技術,以避免讓PDF生成過程超載。

高效的PDF渲染

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

  • 最小化不必要的重渲染:僅當資料重大變更時(例如新增或移除項目)重新生成PDF。
  • 優化表格佈局:當渲染大型數據集時,將其分成更小、更可管理的部分,以改善渲染時間。
  • 使用緩存:為靜態或不頻繁變更的資料緩存先前生成的PDF。

結論

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

ObservableCollection的整合確保您的應用程式始終是最新的,且IronPDF處理生成高品質PDF的繁重工作。 通過遵循本文討論的最佳做法和性能提示,您可以為.NET應用程式創建無縫的PDF生成體驗。

想要親自試用IronPDF嗎? 立即下載免費試用,升級您的C# PDF項目,並務必查看廣泛的文件部分,了解更多此程式庫實際運作的例子。

常見問題解答

什麼是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任務,使開發人員能夠專注於核心應用程序邏輯。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me