所以这是我的编辑器文本更改事件:
private void FormulaEditor_TextChanged(object sender, TextChangedEventArgs e)
{
if(!changedByControls)
{
int oldTextLength = e.OldTextValue?.Length ?? 0;
int newTextLength = e.NewTextValue?.Length ?? 0;
bool textInserted = newTextLength > oldTextLength;
TextAction action = textInserted ? TextAction.Insert : TextAction.Remove;
int textLength = Math.Abs(newTextLength - oldTextLength);
int startIndex = textInserted ? FormulaEditor.CursorPosition : FormulaEditor.CursorPosition - textLength;
string textForOperation = textInserted ? e.NewTextValue: e.OldTextValue;
string text = textForOperation.Substring(startIndex, textLength);
textCommandManager.ChangeText(action, text, startIndex);
UndoButton.IsEnabled = textCommandManager.CanUndo;
}
changedByControls = false;
}
我将解释这里发生的事情。每次当我插入或删除符号或文本的某些部分时,该文本都会通过适当的操作添加到命令列表中。当我插入符号或文本时,一切正常。当我完全删除一个字符或文本时,一切都会正常。但是,例如,当我选择单词的一部分并将其删除时,我会遇到非常奇怪的行为。让我用一个例子来解释一下。假设我将“wasabi”一词复制并粘贴到编辑器中。目前,命令列表包含一个元素,如下所示:
indexOfElement - 0, action - Insert, Position - 0, Text - "wasabi".
现在,例如,我选择了“sabi”一词的一部分,然后单击删除。我注意到,在这种情况下,TextChangedEvent 总是被触发 3 次,然后包含 4 个元素(假设第一个元素是开头插入的单词“wasabi”)。删除这部分单词后,列表如下所示:
indexOfElement - 0, action - Insert, Position - 0, Text - "wasabi";
indexOfElement - 1, action - Remove, Position - 2, Text - "sabi" (this is the value I expected, but unfortunately it is followed by 2 more elements);
indexOfElement - 2, action - Remove, Position - 0, Text - "wa";
indexOfElement - 3, action - Insert, Position - 0, Text - "wa";
任何人都可以解释这种行为的原因以及如何解决它吗?
出于某种原因,视觉工作室更新对我来说很有效。我之前在 github 上读到过这个无法调试的错误,也许现在它已经被修复了。或者可能只是某些图书馆被损坏或其他原因。简而言之,现在一切正常,方法行为符合预期,现在也可以调试文本更改事件(我以前无法做到这一点,我收到一条消息,表明线程中正在运行不兼容的代码)。感谢所有尝试解决我的问题的人