WPF: Как я могу удалить окно поиска в DocumentViewer?
Мой код XAML выглядит так:
<Window
xmlns ='http://schemas.microsoft.com/netfx/2007/xaml/presentation'
xmlns:x ='http://schemas.microsoft.com/winfx/2006/xaml'
Title ='Print Preview - More stuff here'
Height ='200'
Width ='300'
WindowStartupLocation ='CenterOwner'>
<DocumentViewer Name='dv1' ... />
</Window>
Как я могу, в XAML или в C#, исключить окно поиска?
7 ответов
Ответ Влада заставил меня взглянуть на то, как программно получить ContentControl, который содержит панель инструментов поиска. Я действительно не хотел писать совершенно новый шаблон для DocumentViewer; Я хотел изменить (скрыть) только один элемент управления. Это сводит проблему к тому, как получить элемент управления, который применяется через шаблон?,
Вот что я понял:
Window window = ... ;
DocumentViewer dv1 = LogicalTreeHelper.FindLogicalNode(window, "dv1") as DocumentViewer;
ContentControl cc = dv1.Template.FindName("PART_FindToolBarHost", dv1) as ContentControl;
cc.Visibility = Visibility.Collapsed;
Вы можете сделать что-то похожее на ответ Cheeso со стилем ContentControl
и триггер, чтобы скрыть его, когда имя PART_FindToolBarHost
,
<DocumentViewer>
<DocumentViewer.Resources>
<Style TargetType="ContentControl">
<Style.Triggers>
<Trigger Property="Name" Value="PART_FindToolBarHost">
<Setter Property="Visibility" Value="Collapsed" />
</Trigger>
</Style.Triggers>
</Style>
</DocumentViewer.Resources>
</DocumentViewer>
Как указал Влад, вы можете заменить шаблон управления. К сожалению, шаблон управления, доступный в MSDN, не является реальным шаблоном управления, используемым DocumentViewer
контроль. Вот правильный шаблон, измененный, чтобы скрыть панель поиска, установив Visibility="Collapsed"
на PART_FindToolBarHost
:
<!-- DocumentViewer style with hidden search bar. -->
<Style TargetType="{x:Type DocumentViewer}" xmlns:Documents="clr-namespace:System.Windows.Documents;assembly=PresentationUI">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="ContextMenu" Value="{DynamicResource {ComponentResourceKey ResourceId=PUIDocumentViewerContextMenu, TypeInTargetAssembly={x:Type Documents:PresentationUIStyleResources}}}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DocumentViewer}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Focusable="False">
<Grid Background="{TemplateBinding Background}" KeyboardNavigation.TabNavigation="Local">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ContentControl Grid.Column="0" Focusable="{TemplateBinding Focusable}" Grid.Row="0" Style="{DynamicResource {ComponentResourceKey ResourceId=PUIDocumentViewerToolBarStyleKey, TypeInTargetAssembly={x:Type Documents:PresentationUIStyleResources}}}" TabIndex="0"/>
<ScrollViewer x:Name="PART_ContentHost" CanContentScroll="true" Grid.Column="0" Focusable="{TemplateBinding Focusable}" HorizontalScrollBarVisibility="Auto" IsTabStop="true" Grid.Row="1" TabIndex="1"/>
<DockPanel Grid.Row="1">
<FrameworkElement DockPanel.Dock="Right" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}"/>
<Rectangle Height="10" Visibility="Visible" VerticalAlignment="top">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<LinearGradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop Color="#66000000" Offset="0"/>
<GradientStop Color="Transparent" Offset="1"/>
</GradientStopCollection>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
</DockPanel>
<ContentControl x:Name="PART_FindToolBarHost" Grid.Column="0" Focusable="{TemplateBinding Focusable}" Grid.Row="2" TabIndex="2" Visibility="Collapsed"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Вам нужно добавить ссылку на PresentationUI.dll
, Эта сборка находится в папке %WINDIR%\Microsoft.NET\Framework\v4.0.30319\WPF
,
Вы можете заменить контрольный шаблон для него. Для справки: по умолчанию DocumentViewer
Шаблон управления здесь: http://msdn.microsoft.com/en-us/library/aa970452.aspx
Название панели инструментов поиска PART_FindToolBarHost
так что вы также можете просто назначить его Visibility
в Collapsed
,
Редактировать:
Как следует из комментария @Martin, шаблон управления в MSDN (ссылка выше) не является полностью корректным. Лучшим способом извлечь шаблон, который по умолчанию используется в WPF, было бы использование Blend (если не ошибаюсь, измените шаблон управления в контекстном меню).
Чтобы получить ответ Cheeso для работы в конструкторе, мне пришлось добавить:
dv1.ApplyTemplate();
в противном случае cc выходит нулевым. Смотрите ответ здесь
<DocumentViewer>
<DocumentViewer.Resources>
<!-- Toolbar -->
<Style TargetType="ToolBar">
<Setter Property="Visibility" Value="Collapsed" />
</Style>
<!-- Search -->
<Style TargetType="ContentControl">
<Setter Property="Visibility" Value="Collapsed" />
</Style>
</DocumentViewer.Resources>
</DocumentViewer>
Вы уверены, что вам нужен DocumentViewer? Вместо этого вы могли бы использовать FlowDocumentScrollViewer, или, если вам нравится разбивка на страницы или отображение нескольких столбцов, вы можете использовать FlowDocumentPageViewer.