如何在 WPF RichTextBox 中底部对齐文本

2024-04-06

如何在 RichTextBox 中底部对齐文本?貌似控件不直接支持。所以我正在寻找模仿它的方法。理想情况下,我会将控件的边界固定,并将文本结尾与底部对齐。


文本来自 TextBoxBase 的默认控件模板内名为 PART_ContentHost 的 ScrollViewer,该模板由 RichTextBox 包装。您应该覆盖控件模板,并让 ScrollViewer 将其 VerticalAlignment 声明为 Bottom,或者将其模板绑定到 VerticalContentAlignment。

下面,我做了后者。这是从 Blend 中提取的默认控制模板的修改版本。我所做的唯一更改是添加VerticalAlignment="{TemplateBinding VerticalAlignment}"到滚动查看器。

(另请注意,它引用了 Microsoft_Windows_Themes,定义为 xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes; assembly=PresentationFramework.Aero"

我不确定如果 Aero 不在用户的计算机上,这将如何工作)

<Style x:Key="BottomAlignedTextBoxBaseStyle" 
       TargetType="TextBoxBase"
       BasedOn="{StaticResource {x:Type TextBoxBase}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Microsoft_Windows_Themes:ListBoxChrome x:Name="Bd"
                                                        BorderBrush="{TemplateBinding BorderBrush}"
                                                        BorderThickness="{TemplateBinding BorderThickness}"
                                                        Background="{TemplateBinding Background}"
                                                        RenderMouseOver="{TemplateBinding IsMouseOver}"
                                                        RenderFocused="{TemplateBinding IsKeyboardFocusWithin}"                                                       SnapsToDevicePixels="true">
                    <ScrollViewer x:Name="PART_ContentHost"
                                  SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                </Microsoft_Windows_Themes:ListBoxChrome>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled"
                             Value="false">
                        <Setter Property="Background"
                                TargetName="Bd"
                                Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                        <Setter Property="Foreground"
                                Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

然后,要使用它,只需说:

<RichTextBox Style="{StaticResource BottomAlignedTextBoxBaseStyle}" 
             VerticalContentAlignment="Bottom" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 WPF RichTextBox 中底部对齐文本 的相关文章

随机推荐