我想禁用相关按钮。
我的代码是:
<DocumentViewer x:Name="viewerDocument"
Document="{Binding GeneratedDocument}" />
预览如下
您必须重写默认模板(DocumentViewer ControlTemplate 示例)或子类
DocumentViewer
才能重写 DocumentViewerBase.OnPrintCommand
方法并调用 DocumentViewerBase.CancelPrint
方法。您还可以在可视化树中找到打印按钮并将 UIElement.IsEnabled
设置为 false
。
以下示例展示了如何禁用打印按钮:
MainWindow.xaml
<DocumentViewer Loaded="OnDocumentViewerLoaded" />
MainWindow.xaml.cs
private void OnDocumentViewerLoaded(object sender, RoutedEventArgs e)
{
var documentViewer = (DocumentViewer)sender;
Button printButton = documentViewer
.EnumerateVisualChildElements<Button>()
.First(button => button.Command == ApplicationCommands.Print);
// Disable the print button
printButton.IsEnabled = false;
}
private static IEnumerable<TChildren> EnumerateVisualChildElements<TChildren>(DependencyObject parent) where TChildren : DependencyObject
{
for (int childIndex = 0; childIndex < VisualTreeHelper.GetChildrenCount(parent); childIndex++)
{
DependencyObject childElement = VisualTreeHelper.GetChild(parent, childIndex);
if (childElement is Popup popup)
{
childElement = popup.Child;
}
if (childElement is TChildren child)
{
yield return child;
}
foreach (TChildren item in childElement.EnumerateVisualChildElements<TChildren>())
{
yield return item;
}
}
}