簡體   English   中英

在WPF中使用動態數據打印流文檔

[英]Printing a flowdocument with dynamic data in WPF

我試圖找到一種在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包裝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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM