【问题标题】:Printing a flowdocument with dynamic data in WPF在 WPF 中打印带有动态数据的流文档
【发布时间】:2012-12-07 07:50:55
【问题描述】:

我正在尝试找到一种在 WPF 中打印流文档的好方法。我想要的是有可能在我设计文档时看到文档的结果,因此创建一个纯 FlowDocument 作为 XAML 是不可能的(因为 Visual Studio 不会显示它的设计视图)。

所以我现在所做的就是创建一个包含这样的 FlowDocument 的窗口(一些多余的部分已被删除以使代码更简洁):

<Window x:Class="MyNamespace.ProjectPrintout...>
  <Grid>
    <FlowDocumentReader>
      <FlowDocument ColumnWidth="500" Name="Document">
        <!-- Header -->
        <Paragraph Name="HeaderText">
          The header will go here
        </Paragraph>
      </FlowDocument>
    </FlowDocumentReader>
  </Grid>
</Window>

这有点奇怪,因为我永远不会向用户显示这个 Window,我只用一个 Window 包装 FlowDocument,这样我就可以在开发它时看到它的样子。这个我可以忍受。

所以在我的应用程序的其他地方,我想将此 FlowDocument 打印到默认打印机,但我还必须动态设置标题(除了此处省略的需要动态数据的文档的许多其他部分)。

要打印的代码如下所示:

  var printout = new ProjectPrintout();
  printout.HeaderText= new Paragraph(new Run("Proper header text"));
  var document = printout.Document;

  var pd = new PrintDialog();
  IDocumentPaginatorSource dps = document;
  pd.PrintDocument(dps.DocumentPaginator, "Document");

文档正在打印,看起来很好,只是标题文本仍然显示“标题将放在此处”,即使我从代码中将其替换为“正确的标题文本”。我也试过这样改:

(printout.HeaderText.Inlines.FirstInline as Run).Text = "Proper header text";

但结果是一样的。

所以问题是:如何在打印之前从代码中更改 FlowDocument 中的内容,或者有更好的方法来代替我的方法吗?

【问题讨论】:

  • 其实用 (printout.HeaderText.Inlines.FirstInline as Run).Text = "Proper header text";它对我有用
  • @Klaus78 - 我现在测试了,我测试时似乎有 both 行。所以首先 ...HeaderText = new Paragraph... 然后是你提到的那一行。然后它不起作用。如果我只采用你提到的那条线,那么它也适用于我。
  • 知道为什么第一个不起作用吗?似乎将 HeaderText 设置为新的 Paragraph 会将对象 HeaderText 引用更改为新对象,但不会影响 FlowDocument 部分中的对象。相当丑陋的代码,但我至少可以让它工作。谢谢:)
  • 我同意。看起来 HeaderText 是一个新的段落,如果您希望它出现,您需要将其包含在 FlowDocument (yourFlowDoc.Blocks.Add(HeaderText)) 中。

标签: c# .net wpf flowdocument


【解决方案1】:

MVVM 救援:

顿悟:UI 不是数据。 UI 不是数据存储。 UI 旨在显示数据,而不是存储数据。

1 - 创建一个简单的对象来保存您的数据

public class MyDocumentViewModel: INotifyPropertyChanged //Or whatever viewmodel base class
{
    private string _header;
    public string Header 
    {
        get { return _header; }
        set
        {
            _header = value;
            NotifyPropertyChange(() => Header);
         }
     }

     //Whatever other data you need
}

2 - 在您的文档中定义Bindings;

<Paragraph>
    <Run Text="{Binding Header}"/>
</Paragraph>

3 - 将 FlowDocument 的 DataContext 设置为此类的一个实例:

var flowdoc = new YourFlowDocument();
var data = new MyDocumentViewModel { Header = "this is the Header" };
//whatever other data

flowdoc.DataContext = data;

//do the printing stuff.

【讨论】:

    猜你喜欢
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 2016-10-08
    相关资源
    最近更新 更多