Search code examples
c#wpfbuttondata-binding

Disable "Print" button in "DocumentViewer"


I would like to disable the button in question.

My code is:

<DocumentViewer x:Name="viewerDocument" 
                Document="{Binding GeneratedDocument}" />

and the preview is as follows

document viewer


Solution

  • You would have to override the default template (DocumentViewer ControlTemplate Example) or subclass DocumentViewer to override the DocumentViewerBase.OnPrintCommand method and call the DocumentViewerBase.CancelPrint method from the override.
    You can also find the print button in the visual tree and set UIElement.IsEnabled to false.

    The following example shows how to get the print button to disable it:

    MainWindow.xaml

    <DocumentViewer Loaded="OnDocumentViewerLoaded" />
    

    MainWindow.xaml.cs

    private void OnDocumentViewerLoaded(object sender, RoutedEventArgs e)
    {
      var documentViewer = (DocumentViewer)sender;
      Button printButton = EnumerateVisualChildElements<Button>(documentViewer)
        .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 EnumerateVisualChildElements<TChildren>(childElement))
        {
          yield return item;
        }
      }
    }