I am trying to load a FixedDocument from some XAML XML, set it's DataContext, ensure it is bound, and then write it to an XPS. I have code that is doing most of this:
var xaml = (FixedDocument)XamlReader.Parse(@"<FixedDocument> ......</FixedDocument>"); xaml.DataContext = xml; xaml.Dispatcher.Invoke(() => { }, DispatcherPriority.SystemIdle); // generate new XPS document package var mstm = new MemoryStream(); var xpsp = Package.Open(mstm, FileMode.Create, FileAccess.ReadWrite); var xpsd = new System.Windows.Xps.Packaging.XpsDocument(xpsp, CompressionOption.NotCompressed); // write document to package var xpsw = System.Windows.Xps.Packaging.XpsDocument.CreateXpsDocumentWriter(xpsd); xpsw.Write(xaml); xpsp.Flush(); xpsp.Close(); File.WriteAllBytes(@"C:\Users\wasabi\test.xps", mstm.ToArray());
However, the bindings in the FixedDocument are not consistently being applied. Notice the Dispatcher.Invoke line? This is supposed to give the FixedDocument time to evaluate it's binding expressions. However it does not always work. In fact, it
seems to only work on the FIRST RUN of my application from Visual Studio. Subsequent runs do not result in a binding.
My suspicion is that the Binding events are being scheduled in a way that is somewhat dependent on the speed of the code running, and that the second time it runs, something is slightly faster, and so it does not work.
Is there a proper and appropriate way to ensure that the bindings are updated? There is no UI in this application. It is a Windows Service.