多行文本框:在状态栏中显示当前行/字符索引
Posted
技术标签:
【中文标题】多行文本框:在状态栏中显示当前行/字符索引【英文标题】:Multiline Textbox : Display current line/character index in statusbar 【发布时间】:2011-10-15 18:27:49 【问题描述】:我有一个多行文本框,用户可以在其中编辑文本。 在状态栏中,我想显示当前行/字符索引。 我知道我可以获取 CaretIndex,并使用 GetLineIndexFromCharacterIndex 来获取行索引。
但我将如何将其绑定到状态栏?
【问题讨论】:
嗨。同样的问题在这里。 ***.com/questions/8988539/… 【参考方案1】:我会为此使用附加行为。该行为可以通过SelectionChanged
监听变化,并相应地更新两个附加属性CaretIndex
和LineIndex
。
<TextBox Name="textBox"
AcceptsReturn="True"
local:CaretBehavior.ObserveCaret="True"/>
<TextBlock Text="Binding ElementName=textBox,
Path=(local:CaretBehavior.LineIndex)"/>
<TextBlock Text="Binding ElementName=textBox,
Path=(local:CaretBehavior.CaretIndex)"/>
CaretBehavior
public static class CaretBehavior
public static readonly DependencyProperty ObserveCaretProperty =
DependencyProperty.RegisterAttached
(
"ObserveCaret",
typeof(bool),
typeof(CaretBehavior),
new UIPropertyMetadata(false, OnObserveCaretPropertyChanged)
);
public static bool GetObserveCaret(DependencyObject obj)
return (bool)obj.GetValue(ObserveCaretProperty);
public static void SetObserveCaret(DependencyObject obj, bool value)
obj.SetValue(ObserveCaretProperty, value);
private static void OnObserveCaretPropertyChanged(DependencyObject dpo,
DependencyPropertyChangedEventArgs e)
TextBox textBox = dpo as TextBox;
if (textBox != null)
if ((bool)e.NewValue == true)
textBox.SelectionChanged += textBox_SelectionChanged;
else
textBox.SelectionChanged -= textBox_SelectionChanged;
static void textBox_SelectionChanged(object sender, RoutedEventArgs e)
TextBox textBox = sender as TextBox;
int caretIndex = textBox.CaretIndex;
SetCaretIndex(textBox, caretIndex);
SetLineIndex(textBox, textBox.GetLineIndexFromCharacterIndex(caretIndex));
private static readonly DependencyProperty CaretIndexProperty =
DependencyProperty.RegisterAttached("CaretIndex", typeof(int), typeof(CaretBehavior));
public static void SetCaretIndex(DependencyObject element, int value)
element.SetValue(CaretIndexProperty, value);
public static int GetCaretIndex(DependencyObject element)
return (int)element.GetValue(CaretIndexProperty);
private static readonly DependencyProperty LineIndexProperty =
DependencyProperty.RegisterAttached("LineIndex", typeof(int), typeof(CaretBehavior));
public static void SetLineIndex(DependencyObject element, int value)
element.SetValue(LineIndexProperty, value);
public static int GetLineIndex(DependencyObject element)
return (int)element.GetValue(LineIndexProperty);
【讨论】:
【参考方案2】:RichTextBox rtb = new RichTextBox();
int offset = 0;
rtb.CaretPosition.GetOffsetToPosition(rtb.Document.ContentStart);
rtb.CaretPosition.GetPositionAtOffset(offset).GetCharacterRect(LogicalDirection.Forward);
【讨论】:
【参考方案3】:恕我直言,最简单可靠的方法是使用 DispatcherTimer 对 CarteIndex 和 GetLineIndexFromCharacterIndex 成员进行采样。然后为状态栏绑定公开几个 DP 上的值。
【讨论】:
以上是关于多行文本框:在状态栏中显示当前行/字符索引的主要内容,如果未能解决你的问题,请参考以下文章