Print documents via Wpf-controls and convert to XPS

邮差的信 提交于 2019-12-24 15:44:00

问题


I'm trying to convert XAML control to XPS document, but i'd like to do this in batch mode - render control in memory and print it to XPS without rendering it on the screen. This project should work even without GUI.

I've read Related topic on stackoverflow, but it's not working properly. I can create control, set DataContext, but output xps is empty. If i render control on the screen and then print it, everything is ok, but if i'd like to do this in batch mode, i got empty document (there was only static labels etc.)

How can i force control to bind controls with data?

Next hard part would be: how can i add my custom header on each page if i print long-multi-page control? (ex. list?)


回答1:


I'm skipping your second question as it is complex enough to be a standalone.

I faced the same issue, but it may be caused by a couple of different things.

If the issue is because the bindings haven't been "tripped" yet, the solution is slightly hacky but is easy to do if you control the DataContext type. You just add a public or internal method to your type that allows you to fire off PropertyChanged events for each public property. Here's an example:

public interface IForceBinding : INotifyPropertyChanged
{
  void ForceBindings();
}

public class MyDataContext : IForceBinding
{
  public event PropertyChanged;
  private string _text;
  public string Text
  {
    get{return _text;}
    set{_text = value; OnPropertyChanged("Text");}
  }
  public void ForceBindings()
  {
    OnPropertyChanged("Text");
  }

  private void OnPropertyChanged(string propertyName)
  { 
    // you know the drill
  }
}

then, you can use it thusly:

public void Print(MyDataContext preconfiguredContext){
  var page = new MyWpfPage();
  page.DataContext = preconfiguredContext;
  preconfiguredContext.ForceBindings();
  // write to xps

If that isn't working, you might be encountering a bug where the bindings on the first page never show up. I'd have to dig for awhile before I can re-find the solution to that.



来源:https://stackoverflow.com/questions/3807018/print-documents-via-wpf-controls-and-convert-to-xps

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