Printing a flowdocument with dynamic data in WPF

蹲街弑〆低调 提交于 2019-12-08 03:30:33

MVVM to the rescue:

Epiphany: UI is not Data. UI is not a data store. UI is meant to show Data, not to store it.

1 - Create a simple object to hold your data

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 - Define Bindings in your Document;

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

3 - Set your FlowDocument's DataContext to an instance of this class:

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

flowdoc.DataContext = data;

//do the printing stuff.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!