Вот соглашение: Я имею контроль RichTextBox, и он хорошо работает. Проблема состоит в том, что существует кнопка "Insert Current DateTime", которая добавляет/вводит текущую дату и время в RichTextBox. Пользователь может ввести дату и время где угодно, где каре указывает. Это включает сложную обработку строк и материал.
Любые идеи, как получить текущую позицию курсора. Каждый раз, когда я получаю RichTextBox. CaretPositon это кажется им, указывает на запуск RichTextBox и не, где фактическое каре.
ОБНОВЛЕНИЕ 1:
Код нажатия кнопки времени даты:
private void DateTimeStampButton_Click(object sender, RoutedEventArgs e)
{
//TextRange tr = new TextRange(textBox.Selection.Start, textBox.Selection.End);
var tr = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);
if(tr.Text.Length == 2)
{
if(tr.Text == "\r\n")
{
tr.Text = tr.Text.TrimStart(new[] { '\r', '\n' });
}
}
textBox.CaretPosition.InsertTextInRun(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": ");
DateTimeStampButton.Focusable = false;
}
private void SharpRichTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SetValue(TextProperty, Text);
var binding = BindingOperations.GetBinding(this, TextProperty);
if (binding == null) return;
if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default || binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
{
// if (TextProperty != null) BindingOperations.GetBindingExpression(this, TextProperty).UpdateSource();
}
}
public string Text
{
get
{
var newValue = new TextRange(Document.ContentStart, Document.ContentEnd).Text.RemoveNewLineAndReturn();
return newValue;
}
set
{
if (!String.IsNullOrEmpty(value))
{
SetValue(TextProperty, value.RemoveNewLineAndReturn());
Document.Blocks.Clear();
Document.Blocks.Add(new Paragraph(new Run(value)));
OnPropertyChanged("Text");
}
}
}
ОБНОВЛЕНИЕ 2:
Выпущенный проблемой было с кнопкой DateTime быть Focusable. Я повернул его, чтобы быть не focusable, и это работало как ожидалось. Когда фокус был потерян на RichTextBox, он сбрасывал позицию курсора. Это произошло только однажды с тех пор в коде, btn_DateTime динамично устанавливался как Focusable = ложь. Я разместил Focusable = ложь в XAML, и все хорошо работало от запуска.
Я использую этот код, чтобы успешно сделать то, что вы пытаетесь:
private void insertNowButton_Click(object sender, RoutedEventArgs e)
{
//NOTE: The caret position does not change.
richTextBox1.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
}
EDIT: Addressing Update 1
private void DateTimeStampButton_Click(object sender, RoutedEventArgs e)
{
var tr = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);
if (tr.Text.Length == 2)
{
if (tr.Text == "\r\n")
{
tr.Text = tr.Text.TrimStart(new[] { '\r', '\n' });
}
}
/* Changing the text is the only way I can get the date to insert at the beginning */
tr.Text = "I need a beer at ";
textBox.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
}
It looks like SetValue
is changing the text so based my test that actually change the text resets the caret, I would agree with you that SetValue
is causing the problem...