Skip to main content
 首页 » 编程设计

c#之在 WPF 中打印带有动态数据的流文档

2024年02月20日12sky-heaven

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

所以我现在所做的是创建一个包含这样的 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 中的内容,或者是否有更好的方法来代替我的方法?

请您参考如下方法:

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 - 在您的文档中定义Binding;

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