事情是这样的:我有一个 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:
事实证明,问题出在“日期时间”按钮可聚焦上。我把它设置为不可聚焦,并且它按预期工作。当 RichTextBox 失去焦点时,它正在重置插入符号位置。它只发生一次,因为在代码中 btn_DateTime 被动态设置为 Focusable = false。我将 Focusable = false 放置在 XAML 中,从一开始一切都运行良好。
我正在使用此代码成功完成您正在尝试的操作:
private void insertNowButton_Click(object sender, RoutedEventArgs e)
{
//NOTE: The caret position does not change.
richTextBox1.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
}
EDIT:寻址更新 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());
}
看起来像SetValue
正在更改文本,因此根据我的测试,实际更改文本会重置插入符号,我同意你的观点SetValue
导致问题...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)