我为TextBox和ScrollViewer重写了默认模板。现在,当我在TextBox中输入文本时,滚动条(垂直和水平)的滑块不会根据文本大小自动移动。下面是截图。 TextBox Screenshot
ScrollViewer和TextBox的重写模板是:
<Style TargetType="{x:Type TextBox}">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="KeyboardNavigation.TabNavigation" Value="None" />
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="VerticalScrollBarVisibility" Value="Visible"/>
<Setter Property="HorizontalScrollBarVisibility" Value="Visible"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border Name="Border" BorderThickness="1" Background="Black" BorderBrush="#346BAF">
<ScrollViewer x:Name="PART_ContentHost" Style="{DynamicResource TextBoxScrollViewer}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="#222B35"/>
<Setter TargetName="Border" Property="BorderBrush" Value="#696969"/>
<Setter Property="Foreground" Value="#464A51"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="Border" Property="BorderBrush" Value="#00BFFF"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ScrollViewer}">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="HorizontalScrollBarVisibility" Value="Visible"/>
<Setter Property="VerticalScrollBarVisibility" Value="Visible"/>
<Setter Property="MaxHeight" Value="450"/>
<Setter Property="MaxWidth" Value="450"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollContentPresenter Grid.Column="0"/>
<Border Grid.Row="0" Grid.Column="1" BorderBrush="#0080FF" BorderThickness="0,1,1,0">
<ScrollBar Name="PART_VerticalScrollBar" Value="{TemplateBinding VerticalOffset}" Maximum="{TemplateBinding ScrollableHeight}" ViewportSize="{TemplateBinding ViewportHeight}" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"/>
</Border>
<Border Grid.Row="1" Grid.Column="0" BorderBrush="#0080FF" BorderThickness="1,0,0,1">
<ScrollBar Name="PART_HorizontalScrollBar" Orientation="Horizontal" Value="{TemplateBinding HorizontalOffset}" Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/>
</Border>
<Border Grid.Row="1" Grid.Column="1" BorderBrush="#0080FF" BorderThickness="0,0,1,1" Background="#2C446B"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
答案 0 :(得分:0)
每当您向TextBox添加内容时,请收听事件TextChanged。在此方法中,使用此方法:TextBoxBase.ScrollToEnd()。这将始终将滚动条移动到文本的末尾。