【发布时间】:2010-02-08 19:24:48
【问题描述】:
这里是交易:我有一个 RichTextBox 控件,它工作正常。问题是有一个“插入当前日期时间”按钮,它将当前日期时间添加/注入到 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 按钮是可聚焦的。我把它变成不可聚焦的,它按预期工作。当焦点在 RichTextBox 上丢失时,它正在重置插入符号的位置。它只发生了一次,因为在代码中 btn_DateTime 被动态设置为 Focusable = false。我在 XAML 中放置了 Focusable = false 并且从一开始一切都很好。
【问题讨论】:
-
我真希望我知道该告诉你什么。根据文档,RichTextBox 的 CaretPosition 应该是当前位置,或者如果用户没有移动它/键入任何内容,则应该是 RichTextBox 的开始。
-
有没有办法从 CaretPosition 中获取 RichTextBox 输入字符串的索引号。就像字符串是 "hellow" 并且 carret 在 he|llow 那么它应该返回 2。
标签: wpf richtextbox