我的MVVM应用程序使用屏幕上的可视对象将屏幕内容呈现给打印文档。我的视图有ContentControl
使用DataTemplate
资源来确定要显示的内容,但当我尝试将该内容添加到FixedPage
对象时,我会得到一个ArgumentException
消息:
指定的Visual已经是另一个Visual的子项或CompositionTarget的根。
处理打印的视图的(简化)XAML代码如下所示:
<DockPanel>
<!-- Print button -->
<Button DockPanel.Dock="Top"
DataContext="{Binding Path=PrintCommand}"
Click="PrintButton_Click" />
<!-- Print container. -->
<Border BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Top" >
<!-- The visual content of this is what needs adding to the FixedPage. -->
<ContentControl x:Name="printContentControl"
Content="{Binding Path=PrintMe}" />
</Border>
</DockPanel>
...并且具有问题的打印按钮单击处理程序的代码如下所示:
private void PrintButton_Click(object sender, RoutedEventArgs e)
{
// Get a reference to the Visual objects to be printed.
var content = VisualTreeHelper.GetChild(printContentControl, 0);
Debug.Assert((content as UIElement) != null, "Print content is not a UIElement");
#region This doesn't work. See below for other things that also don't work.
printContentControl.Content = null;
// The line below doesn't help, but tried it in case the framework
// needed a poke to get it to update the visual tree.
UpdateLayout();
#endregion
// Make sure that all the data binding, layout, etc. has completed
// before the visual object is printed by queuing the print job at
// a later priority.
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(delegate()
{
// Create a fixed page to hold the content to print.
FixedPage page = new FixedPage();
// Add the content to print to the page.
#region Here be dragons: 'System.ArgumentException'
page.Children.Add(content as UIElement);
#endregion
// Send the document back to the View model for actual printing.
var command = ((sender as Button).DataContext as ICommand);
command.Execute(page);
}));
}
我已经尝试了以下方法来解决问题,但都没有成功:
Content
的{{1}}成员设置为null(如上面的代码所示)。ContentControl
。屏幕变为空白,但仍然有例外。this.Content=null
。这些都没有效果。RemoveLogicalChild()
和RemoveVisualChild()
对象上使用printContentControl
。这些都不是当前对象的孩子。content
的{{1}}或DataTrigger
为“{x:Null}”时,使用XAML中的Content
替换模板。没效果。屏幕外观是否混乱并不重要,因为DataContext
在执行打印命令时会更改ContentControl
。
如何将ViewModel
的可视内容(或整个控件)从View
的可视树移动到printContentControl
的{{1}}对象?
肮脏的解决方法
通过为要打印的内容创建包装类,我可以使功能正常工作,但它不能回答原始问题。
包装类
View
使用包装器更新XAML以保存可打印内容
ViewModel
更新后面的代码以从包装器中获取可打印内容
FixedPage