我正在将很多富文本加载到RichTextBox
(WPF)中,我想滚动到内容的结尾:
richTextBox.Document.Blocks.Add(...)
richTextBox.UpdateLayout();
richTextBox.ScrollToEnd();
这不起作用,当布局没有完成时执行ScrollToEnd
,所以它不滚动到结尾,它滚动到文本的前三分之一左右。
是否有办法迫使等待,直到RichTextBox
完成其绘画和布局操作,以便ScrollToEnd
实际滚动到文本的末尾?
谢谢。
不起作用的东西:
编辑:我已经尝试了LayoutUpdated
事件,但它立即被解雇,同样的问题:当它被解雇时控件仍然在richtextbox内部布置更多文本,所以即使是ScrollToEnd
也没有用...我试过这个:
richTextBox.Document.Blocks.Add(...)
richTextBoxLayoutChanged = true;
richTextBox.UpdateLayout();
richTextBox.ScrollToEnd();
并在richTextBox.LayoutUpdated
事件处理程序内:
if (richTextBoxLayoutChanged)
{
richTextBoxLayoutChanged = false;
richTextBox.ScrollToEnd();
}
事件被正确触发但是太快了,当它被触发时,richtextbox仍然添加更多文本,布局没有完成,所以ScrollToEnd
再次失败。
编辑2:关注dowhilefor的回答:InvalidateArrange上的MSDN说
失效后,元素将更新其布局,除非随后由UpdateLayout强制,否则将以异步方式进行。
甚至
richTextBox.InvalidateArrange();
richTextBox.InvalidateMeasure();
richTextBox.UpdateLayout();
不要等待:在这些调用之后,richtextbox仍然会添加更多文本并异步地将其放在自身内部。 ARG!
特别:
如果布局未更改,或者布局的布局和测量状态均无效,则调用此方法无效
因此,根据您的需要调用InvalidateMeasure或InvalidateArrange应该可以正常工作。
但考虑到你的代码。我认为这不会奏效。很多WPF加载和创建都被保留,因此向Document.Blocks添加内容并不直接改变UI。但我必须说,这只是一个猜测,也许我错了。
我有一个相关的情况:我有一个打印预览对话框,创建一个奇特的渲染。通常,用户将单击一个按钮来实际打印它,但我也想用它来保存图像而无需用户参与。在这种情况下,创建图像必须等到布局完成。
我使用以下方法管理:
Dispatcher.Invoke(new Action(() => {SaveDocumentAsImage(....);}), DispatcherPriority.ContextIdle);
关键是DispatcherPriority.ContextIdle
,等待后台任务完成。
编辑:根据Zach的请求,包括适用于此特定案例的代码:
Dispatcher.Invoke(() => { richTextBox.ScrollToEnd(); }), DispatcherPriority.ContextIdle);
我应该注意到,我对这个解决方案并不满意,因为它感觉非常脆弱。但是,它似乎确实适用于我的具体情况。
尝试添加richTextBox.ScrollToEnd();调用RichTextBox对象的LayoutUpdated事件处理程序。
你应该能够使用Loaded事件
如果你这样做超过一次,那么你应该看看LayoutUpdated事件
myRichTextBox.LayoutUpdated += (source,args)=> ((RichTextBox)source).ScrollToEnd();
使用.net 4.5或async blc包,您可以使用以下扩展方法
/// <summary>
/// Async Wait for a Uielement to be loaded
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static Task WaitForLoaded(this FrameworkElement element)
{
var tcs = new TaskCompletionSource<object>();
RoutedEventHandler handler = null;
handler = (s, e) =>
{
element.Loaded -= handler;
tcs.SetResult(null);
};
element.Loaded += handler;
return tcs.Task;
}
@Andreas的答案很有效。
但是,如果控件已加载怎么办?事件永远不会发生,等待可能会永远停止。要解决此问题,请在表单已加载后立即返回:
/// <summary>
/// Intent: Wait until control is loaded.
/// </summary>
public static Task WaitForLoaded(this FrameworkElement element)
{
var tcs = new TaskCompletionSource<object>();
RoutedEventHandler handler = null;
handler = (s, e) =>
{
element.Loaded -= handler;
tcs.SetResult(null);
};
element.Loaded += handler;
if (element.IsLoaded == true)
{
element.Loaded -= handler;
tcs.SetResult(null);
}
return tcs.Task;
}
这些提示可能有用也可能没用。
task.Yield()
将调用放到调度程序队列的后面:
await Task.Yield(); // Put ourselves to the back of the dispatcher queue.
PopWindowToForegroundNow = false;
await Task.Yield(); // Put ourselves to the back of the dispatcher queue.
PopWindowToForegroundNow = false;
Loaded
:
// Ensure PopWindowToForegroundNow is initialized to true
// (attached properties only trigger when the value changes).
Application.Current.Dispatcher.Invoke(
async
() =>
{
if (PopWindowToForegroundNow == false)
{
// Already visible!
}
else
{
await Task.Yield(); // Put ourselves to the back of the dispatcher queue.
PopWindowToForegroundNow = false;
}
}, DispatcherPriority.Loaded);
试试这个:
richTextBox.CaretPosition = richTextBox.Document.ContentEnd;
richTextBox.ScrollToEnd(); // maybe not necessary
为我的WPF项目工作的唯一(kludge)解决方案是启动一个单独的线程,该线程睡了一段时间,然后要求滚动到最后。
重要的是不要尝试在主GUI上调用这个“困”线程,以免用户暂停。因此,在主GUI线程上调用一个单独的“困”线程并定期调用Dispatcher.Invoke并要求滚动到结尾。
工作完美,用户体验并不可怕:
using System;
using System.Threading;
using System.Windows.Controls;
try {
richTextBox.ScrollToEnd();
Thread thread = new Thread(new ThreadStart(ScrollToEndThread));
thread.IsBackground = true;
thread.Start();
} catch (Exception e) {
Logger.Log(e.ToString());
}
和
private void ScrollToEndThread() {
// Using this thread to invoke scroll to bottoms on rtb
// rtb was loading for longer than 1 second sometimes, so need to
// wait a little, then scroll to end
// There was no discernable function, ContextIdle, etc. that would wait
// for all the text to load then scroll to bottom
// Without this, on target machine, it would scroll to the bottom but the
// text was still loading, resulting in it scrolling only part of the way
// on really long text.
// Src: https://stackoverflow.com/questions/6614718/wait-until-control-layout-is-finished
for (int i=1000; i <= 10000; i += 3000) {
System.Threading.Thread.Sleep(i);
this.richTextBox.Dispatcher.Invoke(
new ScrollToEndDelegate(ScrollToEnd),
System.Windows.Threading.DispatcherPriority.ContextIdle,
new object[] { }
);
}
}
private delegate void ScrollToEndDelegate();
private void ScrollToEnd() {
richTextBox.ScrollToEnd();
}