gpt4 book ai didi

wpf - RichTextBox 并在插入符号位置插入

转载 作者:行者123 更新时间:2023-12-04 13:18:05 27 4
gpt4 key购买 nike

这是交易:我有一个 RichTextBox 控件,它工作正常。问题是有一个“插入当前日期时间”按钮,它将当前日期时间添加/注入(inject)到 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 并且从一开始一切都很好。

最佳答案

我正在使用此代码成功地执行您正在尝试的操作:

private void insertNowButton_Click(object sender, RoutedEventArgs e)
{
//NOTE: The caret position does not change.
richTextBox1.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
}

编辑:解决更新 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导致问题...

关于wpf - RichTextBox 并在插入符号位置插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2224243/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com