【发布时间】:2011-09-05 17:48:28
【问题描述】:
如何在 RichTextBox 中对齐文本?似乎控件不直接支持它。所以我正在寻找模仿它的方法。理想情况下,我会将控件的边界固定并且文本的结尾与底部对齐。
【问题讨论】:
标签: wpf wpf-controls richtextbox vertical-alignment text-alignment
如何在 RichTextBox 中对齐文本?似乎控件不直接支持它。所以我正在寻找模仿它的方法。理想情况下,我会将控件的边界固定并且文本的结尾与底部对齐。
【问题讨论】:
标签: wpf wpf-controls richtextbox vertical-alignment text-alignment
文本来自 TextBoxBase 的默认控件模板中名为 PART_ContentHost 的 ScrollViewer,该模板由 RichTextBox 包装。您应该覆盖控件模板并让 ScrollViewer 将其 VerticalAlignment 声明为 Bottom,或者将其模板绑定到 VerticalContentAlignment。
下面,我已经完成了后者。这是从 Blend 中提取的默认控件模板的修改版本。我所做的唯一更改是将 VerticalAlignment="{TemplateBinding VerticalAlignment}" 添加到 ScrollViewer。
(另请注意,它引用了 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" />
【讨论】: