我正在开发一个基于RichEditBox的文本编辑器。我已经实现了"Go to line“功能,它最终会解析为TextPointer.Paragraph.BringIntoView();
同时,我还设置了插入符号的位置。我发现只有当我首先点击RichEditBox (聚焦它)时,BringIntoView才能工作。否则,它似乎会被忽略。我可以看到插入符号的位置已经通过BringIntoView周围的代码进行了调整。
有人知道这个问题的原因/本质是什么吗?我怎样才能克服它?
发布于 2013-10-13 06:58:55
我找到了一个解决方法,不确定它是否能在纯WPF环境中工作,在我的例子中,我在一个主要使用WPF UserControls的Windows Forms解决方案中运行WPF。
不是立即调用BringIntoFocus(),而是通过将其添加到由计时器处理的队列中,将其推迟到稍后的时刻。例如:
System.Windows.Forms.Timer DeferredActionTimer = new System.Windows.Forms.Timer() { Interval = 200 };
Queue<Action> DeferredActions = new Queue<Action>();
void DeferredActionTimer_Tick(object sender, EventArgs e) {
while(DeferredActions.Count > 0) {
Action act = DeferredActions.Dequeue();
act();
}
}在窗体构造函数或OnLoad事件中添加:
DeferredActionTimer.Tick += new EventHandler(DeferredActionTimer_Tick);
DeferredActionTimer.Enabled = true;最后,不要直接调用TextPointer.Paragraph.BringIntoView();,而是像这样调用它:
DeferredActions.Enqueue(() => TextPointer.Paragraph.BringIntoView());请注意,Windows窗体计时器在主线程中启动事件(通过消息泵循环)。如果你必须使用另一个计时器,你需要一些额外的代码。我建议您使用System.Timers.Timer而不是System.Threading.Timer (它的线程安全性更高)。您还必须将操作包装在Dispatcher.Invoke结构中。在我的例子中,WinForms定时器的作用就像一个护身符。
发布于 2009-10-26 16:45:59
你就不能把RichTextBox(?)首先聚焦,然后使用Keyboard.Focus(richTextBox)或richTextBox.Focus()
https://stackoverflow.com/questions/1614360
复制相似问题