多行文本框:在状态栏中显示当前行/字符索引 [英] Multiline Textbox : Display current line/character index in statusbar
本文介绍了多行文本框:在状态栏中显示当前行/字符索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多行文本框,用户可以在其中编辑文本。
在状态栏中,我想显示当前的行/字符索引。
我知道我可以获得CaretIndex,并使用GetLineIndexFromCharacterIndex来获取行索引。
I have a multiline textbox where the user can edit text. In a statusbar I'd like to show the current line / character index. I know I can get the CaretIndex, and use GetLineIndexFromCharacterIndex to get the line-index.
但是我如何将其绑定到状态栏?
But how would I go about binding that into the statusbar ?
推荐答案
我会使用附加行为。该行为可以使用 SelectionChanged
侦听更改并更新两个附加属性 CaretIndex
和 LineIndex
相应。
I'd use an attached behavior for that. The behavior can listens to changes with SelectionChanged
and update two attached properties CaretIndex
and LineIndex
accordingly.
<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);
}
}
这篇关于多行文本框:在状态栏中显示当前行/字符索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文