问题
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