.NET ヘルプ

C# ObservableCollection(開発者向けの動作方法)

イントロダクション

C#では、ObservableCollection は、要素が追加、削除、または変更されたときにリスナーに自動的に通知する強力なデータ構造です。 これは、UIやレポートにリアルタイムの変更を反映する必要がある場合など、動的データ収集シナリオで特に役立ちます。 IronPDFと組み合わせると、この強力なコレクションを使用して、ライブデータに基づいて動的なPDFを生成できます。

IronPDF は、C#でPDFを生成するための強力なライブラリです。 そのHTML-to-PDF変換機能により、請求書、レポート、またはリアルタイムデータに基づくその他のドキュメントを生成する必要がある場合でも、高品質のPDFを簡単に作成できます。 この記事では、データバインディングを活用して、データの変化に応じて動的に更新されるPDFを生成するために、ObservableCollectionクラスをIronPDFと統合する方法を紹介します。

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

Pixabay から追加アップロード

またはここに画像をドラッグアンドドロップします

画像の代替テキストを追加

この記事の冒頭で述べたように、IronPDFはPDFドキュメントの作成、修正、およびレンダリングを容易にする.NET PDF生成ライブラリです。 他のいくつかのPDFライブラリとは異なり、IronPDFは、HTMLをPDFに変換する、ウォーターマークを追加する、既存のPDFを操作するなど、PDFを扱う作業を簡素化する豊富な機能を提供します。

IronPDFは、HTML、画像、プレーンテキストなどのさまざまなデータソースからPDFをレンダリングすることもでき、特に動的データを提示する必要がある場合に役立ちます。 IronPDFのAPIを使用すると、高品質なPDFを生成でき、詳細なレイアウト、テーブル、画像、スタイルを含めることができます。

IronPDFセットアップ

IronPDFを始めるには、NuGetを通じてライブラリをインストールする必要があります。 パッケージ マネージャー コンソールで次のコマンドを実行して、プロジェクトに追加できます:

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

インストール後、IronPDF を初期化して、その強力な機能を使用できます。 この記事では、ObservableCollectionの動的データからPDFを生成することに焦点を当てます。

ObservableCollectionをIronPDFと統合する

ユースケース: ObservableCollection から動的にPDFを生成する

リストに格納された項目から請求書PDFを生成する必要があるシナリオを想像してみましょう。 コレクションにアイテムが追加または削除されると、データの現在の状態を反映するためにPDFが自動的に再生成される必要があります。

このタスクでは、ObservableCollectionは請求書の項目を管理する簡単な方法を提供し、IronPDFは請求書をPDF形式で生成およびエクスポートすることを可能にします。

PDFコンテンツへのデータバインディング

ObservableCollectionのデータをPDFにバインドするには、コレクションをループしてそのアイテムをPDFコンテンツに追加する必要があります。 IronPDFは、データを構造化された形式で表現するために、テーブルを作成する方法、テキストを追加する方法、レイアウトをカスタマイズする方法を提供します。

たとえば、複数の項目を含む請求書がある場合、ObservableCollection をループして各項目をドキュメント内のテーブルやリストに追加することで、PDF を動的に生成できます。 IronPDFは、フォントや枠線の調整、さらにはロゴやバーコードなどの画像の挿入を含め、高度なカスタマイズが可能です。

例1: 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; }
}
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オブジェクトのコレクションが含まれています。 アイテムが追加または削除されると、イベントハンドラーがトリガーされ、それを使用してPDFを動的に更新します。

コレクションの変更に対するイベントハンドラーの追加

この例では、コレクションが変更されるたびにPDFを自動的に再生成するために、ObservableCollectionクラスのCollectionChangedイベントを購読します。 これは、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が再生成され、新しいエントリが含まれます。

年齢プロパティのバインディング

また、age プロパティを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

例2: 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に変換します。そして、そのHTMLをIronPDFを使用して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 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

ステップ 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 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

出力

C# ObservableCollection(開発者向けの動作原理):図2 - 出力PDFファイル

Pixabay から追加アップロード

またはここに画像をドラッグアンドドロップします

代替テキストをクリア

コードの説明

  • 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を試してみたいですか? 豊富なドキュメントセクションも必ず確認してください。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
次へ >
C# XOR(開発者向けの動作原理)