我有几个只用于记录输出的RichTextBox。因为它们是只读的,所以在更新文本时,它们似乎不会自动滚动。我可以使用TextChanged事件强制滚动结束,但是是否有一种简单的方法可以在XAML中设置属性或其他东西,这样滚动就可以正常进行了吗?
发布于 2012-04-25 04:57:31
我在谷歌上搜索了你的问题,找到了this帖子。在“编程RichTextBox”一节中,作者描述了如何得到您所期望的行为。
请检查一下,如果有什么用,请告诉我。
我试图重现您的问题,并提出了以下解决方案
<Window x:Class="CheckRichTextBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="170" Width="300">
<StackPanel>
<RichTextBox Height="100" Name="richTextBox1" IsReadOnly="True" VerticalScrollBarVisibility="Visible"/>
<Button Name="btnAdd" Content="Click me to add text" VerticalAlignment="Bottom" Click="BtnAddClick" />
</StackPanel>
</Window>
相同代码后面的代码如下:
using System.Windows;
namespace CheckRichTextBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnAddClick(object sender, RoutedEventArgs e)
{
richTextBox1.AppendText("You had Clicked the button for adding text\n");
richTextBox1.ScrollToEnd();
}
}
}
这解决了自动投币机的问题,请检查一下,如果有什么帮助,请告诉我。
发布于 2014-01-20 16:11:23
我使用一个Interactivity触发器和一个非常简单的操作解决了这个问题。
行动看起来是这样的:
public class ScrollToBottomAction : TriggerAction<RichTextBox>
{
protected override void Invoke(object parameter)
{
AssociatedObject.ScrollToEnd();
}
}
在我的XAML中我有这样一个:
<RichTextBox IsReadOnly="True" VerticalScrollBarVisibility="Auto">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<interactivity:ScrollToBottomAction/>
</i:EventTrigger>
</i:Interaction.Triggers>
</RichTextBox>
发布于 2021-10-08 01:54:16
我为wpf richtextbox提供了以下解决方案
public partial class MainWindow
{
private bool AutoScroll = true;
public MainWindow()
{
InitializeComponent();
yourRichTextBox.Loaded += (s, e) =>
{
var scrollViewer = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(yourRichTextBox, 0), 0) as ScrollViewer;
scrollViewer.ScrollChanged += (scroller, eScroller) => ScrollViewer_ScrollChanged(scroller, eScroller);
};
}
private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
// User scroll event : set or unset autoscroll mode
if (e.Source as ScrollViewer != null && e.ExtentHeightChange == 0)
{ // Content unchanged : user scroll event
if ((e.Source as ScrollViewer).VerticalOffset == (e.Source as ScrollViewer).ScrollableHeight)
{ // Scroll bar is in bottom
// Set autoscroll mode
AutoScroll = true;
}
else
{ // Scroll bar isn't in bottom
// Unset autoscroll mode
AutoScroll = false;
}
}
// Content scroll event : autoscroll eventually
if (AutoScroll && e.ExtentHeightChange != 0 && e.Source as ScrollViewer != null)
{ // Content changed and autoscroll mode set
// Autoscroll
(e.Source as ScrollViewer).ScrollToVerticalOffset((e.Source as ScrollViewer).ExtentHeight);
}
}
}
https://stackoverflow.com/questions/10308475
复制相似问题