我有一個多行文本框,用戶可以在其中編輯文本。 在狀態欄中,我想顯示當前行/字符索引。 我知道我可以得到CaretIndex,並使用GetLineIndexFromCharacterIndex來獲取行索引。多行文本框:在狀態欄中顯示當前行/字符索引
但是,我會如何將綁定到狀態欄?
我有一個多行文本框,用戶可以在其中編輯文本。 在狀態欄中,我想顯示當前行/字符索引。 我知道我可以得到CaretIndex,並使用GetLineIndexFromCharacterIndex來獲取行索引。多行文本框:在狀態欄中顯示當前行/字符索引
但是,我會如何將綁定到狀態欄?
RichTextBox rtb = new RichTextBox();
int offset = 0;
rtb.CaretPosition.GetOffsetToPosition(rtb.Document.ContentStart);
rtb.CaretPosition.GetPositionAtOffset(offset).GetCharacterRect(LogicalDirection.Forward);
IMHO,最簡單的和可靠的方法是採樣兩者CarteIndex並使用DispatcherTimer的GetLineIndexFromCharacterIndex成員。然後在狀態欄綁定上暴露幾個DP的值。
我會使用附加的行爲。該行爲可以通過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);
}
}
嗨。這裏同樣的問題。 http://stackoverflow.com/questions/8988539/richtextbox-selectionstart-returns-wrong-index – Nasenbaer