我找到了解决方案。
将此添加到 XAML
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Print" PreviewExecuted="CommandBinding_PreviewExecuted" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
这就是背后的代码
private void CommandBinding_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
PrintDialog dialog = new PrintDialog();
if (dialog.ShowDialog() == true)
{
dialog.PrintDocument(Document.DocumentPaginator, "Print Job Title");
}
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
//needed so that preview executed works
}
有几点需要注意。如果未绑定 Exectued 事件,则不会发生 PreviewExecuted 方法。不知道为什么。