且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过 Wpf-controls 打印文档并转换为 XPS

更新时间:2023-11-14 08:07:58

我将跳过您的第二个问题,因为它足够复杂,可以独立使用.

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.

如果问题是因为绑定还没有被绊倒",那么解决方案有点麻烦,但如果您控制 DataContext 类型,则很容易做到.您只需向您的类型添加一个公共或内部方法,允许您为每个公共属性触发 PropertyChanged 事件.举个例子:

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.