WPF 文本框我想添加一个撤消/重做,就像按下向上和向下箭头键时的命令提示符一样

本文关键字:一样 命令提示符 添加 文本 一个 WPF 重做 撤消 | 更新日期: 2023-09-27 18:36:11

我想将命令行提示符中的功能添加到我的 WPF 文本框中。 当用户按下向上箭头时,在命令 propmpt 中,将显示使用的上一个命令。 如果他继续按向上箭头,就会看到下一个上一个文本。 如果用户向下推,那么它将再次走向另一个方向。

实现这一目标的最佳方法是什么? (内置的重做/撤消在文档级别上比我要求的更多。

WPF 文本框我想添加一个撤消/重做,就像按下向上和向下箭头键时的命令提示符一样

您可以使用撤消和重做应用程序命令。这是不符合 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;
    }
}

我希望这就是你的意思。

您可以简单地使用 PreviewKeyDown 事件并检查 Key.Down 或 Key.Up 并读取最后命令的列表。如果设置 e.Handle = 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,您可以使用事件触发器来触发视图模型中的命令。希望这能给你带来想法。不幸的是,我没有足够的时间为您编程。:)

您可以将命令保存到堆栈集合中。