我有一个多行文本框,用户可以在其中编辑文本。 在状态栏中,我想显示当前的行/字符索引。 我知道我可以获得CaretIndex,并使用GetLineIndexFromCharacterIndex来获取行索引。
但是我如何将其绑定到状态栏?
答案 0 :(得分:2)
我会使用附加行为。该行为可以使用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);
}
}
答案 1 :(得分:0)
RichTextBox rtb = new RichTextBox();
int offset = 0;
rtb.CaretPosition.GetOffsetToPosition(rtb.Document.ContentStart);
rtb.CaretPosition.GetPositionAtOffset(offset).GetCharacterRect(LogicalDirection.Forward);
答案 2 :(得分:0)
恕我直言,最简单可靠的方法是使用DispatcherTimer对CarteIndex和GetLineIndexFromCharacterIndex成员进行采样。然后在几个DP上公开值以获取状态栏绑定。