如何通过WPF代码以舒适的方式创建FlowDocuments?

时间:2011-12-05 18:54:55

标签: c# .net wpf flowdocument

我需要生成一些报告,所选格式是FlowDocuments。当我通过代码生成它们时,我发现自己一直在做这样的事情:

list.ListItems.Add(new ListItem(new Paragraph(new Run(string.Format("XXX XXXXXX: {0}", _result.XXX.Count)))));
list.ListItems.Add(new ListItem(new Paragraph(new Run(string.Format("XXX XXXXXX: {0}", _result.XXX())))));
list.ListItems.Add(new ListItem(new Paragraph(new Run(string.Format("XXX XXXXXX: {0}", _result.LossOperations())))));

当我必须添加一行文字时,我必须执行以下操作:

Paragraph auxParagraph = new Paragraph();
auxParagraph.Inlines.Add("Executing time " + _result.ExecutingTime.ToString());
report.Blocks.Add(auxParagraph);

对我来说有点矫枉过正了。我正在以正确的方式使用API​​?我只看到有关手工创建文档的文档。也许它们不是由代码创建的,我们应该检查另一种格式吗?或者是否有其他更高级别的API可以更轻松地使用FlowDocuments?

谢谢!

编辑:使用表格的另一个例子:

foreach (DateTime availableDay in _result.Generator.AvailableDays)
        {
            Table table = new Table();
            table.Columns.Add(new TableColumn());
            table.Columns.Add(new TableColumn());
            table.Columns.Add(new TableColumn());
            table.Columns.Add(new TableColumn());
            table.Columns.Add(new TableColumn());

            TableRowGroup headers = new TableRowGroup();
            TableRow headersRow = new TableRow();

            headersRow.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
            headersRow.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
            headersRow.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
            headersRow.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
            headersRow.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));

            headers.Rows.Add(headersRow);
            table.RowGroups.Add(headers);

            DateTime day = availableDay;

            TableRowGroup valuesGroup = new TableRowGroup();
            foreach (Operation operation in dailyOperations)
            {
                TableRow row = new TableRow();
                row.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
                row.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
                row.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
                row.Cells.Add(new TableCell(new Paragraph(new Run("XXX XXXX"))));
                row.Cells.Add(new TableCell(CreateColoredValue(operation.Result)));
                valuesGroup.Rows.Add(row);
            }
            table.RowGroups.Add(valuesGroup);

            result.Blocks.Add(table);
        }

1 个答案:

答案 0 :(得分:1)

您的号码列表是一种特殊情况。我会创建一些重载方法:

static Paragraph P(string fmt, object[] params) { ... }
static Paragraph P(string s) { return P(new Run(s)); } 
static Paragraph P(Run r)    { return new Paragraph(r); }

你会有

list.ListItems.Add(new ListItem(P("XXX XXXXXX: {0}", _result.XXX.Count)));

你可以用ListItem,Block等几种方法进一步驯服它。