问题描述
我正在使用WPF开发记事本应用程序.如何获取文本框中的当前光标位置,并将其显示在状态栏按钮中.
任何帮助将不胜感激.
谢谢.
I am developing a notepad application using WPF. How can I get the current cursor position in a textbox and display it in the statusbar button.
Any help is greatly appreciated.
Thanks.
推荐答案
private void textBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
int s = textBox1.SelectionStart;
// get the first status bar item
System.Windows.Controls.Primitives.StatusBarItem item = (System.Windows.Controls.Primitives.StatusBarItem)this.statusBar1.Items[0];
// get the content textblock of the status bar item
item.Content = s.ToString();
}
我只在状态栏中使用了一项,但是您可以通过更改
I''ve only used one item in my status bar, but you can change the relevant item by changing the
this.statusBar1.Items[0];
internal void InquireCaretPosition(out Position line, out Position column) {
line = 0; column = 0;
int caret = this.CaretIndex;
int iLine = this.GetLineIndexFromCharacterIndex(caret);
if (iLine < 0) iLine = 0;
line = iLine;
int firstChar = this.GetCharacterIndexFromLineIndex(iLine);
if (firstChar < 0) firstChar = 0;
column = caret - firstChar;
} //InquireCaretPosition
此代码应使用从TextBox
继承的类编写.
另一个问题:在状态栏上显示插入符号位置的事件有哪些?
1)覆盖方法OnSelectionChanged
;
2)首次显示文本框控件实例时;
3)如果您有多个文本框控件;当您选择/显示其中之一时.
如果我没记错的话,它将涵盖所有情况.
This code should be written in class inheriting from TextBox
.
Another problem: on what events to show the caret position in the status bar?
1) Overridden method OnSelectionChanged
;
2) When your text box control instance is first shown;
3) If you have more then one text box controls; when you select/show one of them.
If I''m not much mistaken, it will cover all cases.
这篇关于如何在文本框中获取光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!