WPF TextBox 我想在按下向上和向下箭头键时像命令提示符一样添加撤消/重做
WPF TextBox I would like to add a undo / redo like the command prompt when the up and down arrow keys are pushed
我想将命令行提示符中的功能添加到我的 WPF TextBox 中。在命令提示符中,当用户按下向上箭头时,将出现上一个使用的命令。如果他一直按向上箭头,就会看到下一个上一个文本。如果用户向下推,它会再次向相反方向移动。
完成此任务的最佳方法是什么? (内置的重做/撤消在文档级别上的工作比我需要的更多。)
您可以将命令保存到堆栈集合中。
您可以简单地使用 PreviewKeyDown 事件并检查 Key.Down 或 Key.Up 并阅读您最后的命令列表。如果设置 e.Handled = true 光标不会向上跳。
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
{
e.Handled = true;
//Here comes the code where you read your last commands and print it to your Textbox
}
//Same for Key.Down
}
为了使其符合 MVVM,您可以使用事件触发器来触发视图模型中的命令。
希望这能给你灵感。不幸的是我没有足够的时间为你编程。 :)
您可以使用撤消和重做应用程序命令。
这是 MVVM 不兼容的版本:
在你的XAML
<TextBox Margin="5" PreviewKeyUp="TextBox_PreviewKeyUp" AcceptsReturn="False" />
在你的代码隐藏中
private List<string> _history = new List<string>();
private int _historyIndex = -1;
private void TextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
TextBox textBox = (TextBox)sender;
if (e.Key == Key.Return)
{
_history.Add(textBox.Text);
if (_historyIndex < 0 || _historyIndex == _history.Count - 2)
{
_historyIndex = _history.Count - 1;
}
textBox.Text = String.Empty;
return;
}
if (e.Key == Key.Up)
{
if (_historyIndex > 0)
{
_historyIndex--;
textBox.Text = _history[_historyIndex];
}
return;
}
if (e.Key == Key.Down)
{
if (_historyIndex < _history.Count - 1)
{
_historyIndex++;
textBox.Text = _history[_historyIndex];
}
return;
}
}
希望这就是您要的功能。
我想将命令行提示符中的功能添加到我的 WPF TextBox 中。在命令提示符中,当用户按下向上箭头时,将出现上一个使用的命令。如果他一直按向上箭头,就会看到下一个上一个文本。如果用户向下推,它会再次向相反方向移动。
完成此任务的最佳方法是什么? (内置的重做/撤消在文档级别上的工作比我需要的更多。)
您可以将命令保存到堆栈集合中。
您可以简单地使用 PreviewKeyDown 事件并检查 Key.Down 或 Key.Up 并阅读您最后的命令列表。如果设置 e.Handled = true 光标不会向上跳。
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
{
e.Handled = true;
//Here comes the code where you read your last commands and print it to your Textbox
}
//Same for Key.Down
}
为了使其符合 MVVM,您可以使用事件触发器来触发视图模型中的命令。 希望这能给你灵感。不幸的是我没有足够的时间为你编程。 :)
您可以使用撤消和重做应用程序命令。 这是 MVVM 不兼容的版本:
在你的XAML
<TextBox Margin="5" PreviewKeyUp="TextBox_PreviewKeyUp" AcceptsReturn="False" />
在你的代码隐藏中
private List<string> _history = new List<string>();
private int _historyIndex = -1;
private void TextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
TextBox textBox = (TextBox)sender;
if (e.Key == Key.Return)
{
_history.Add(textBox.Text);
if (_historyIndex < 0 || _historyIndex == _history.Count - 2)
{
_historyIndex = _history.Count - 1;
}
textBox.Text = String.Empty;
return;
}
if (e.Key == Key.Up)
{
if (_historyIndex > 0)
{
_historyIndex--;
textBox.Text = _history[_historyIndex];
}
return;
}
if (e.Key == Key.Down)
{
if (_historyIndex < _history.Count - 1)
{
_historyIndex++;
textBox.Text = _history[_historyIndex];
}
return;
}
}
希望这就是您要的功能。