ashlar64
ashlar64

Reputation: 1094

WPF TextBox I would like to add a undo / redo like the command prompt when the up and down arrow keys are pushed

I would like to add the functionality that is found in the command line prompt into my WPF TextBox. In the command propmpt when the user pushes the up arrow the previous command that was used will appear. And if he keeps pushing the up arrow the next previous text will be seen. And if the user pushes down then it will go the other way again.

What would be the best way to accomplish this? (The built in redo / undo works more on a document level than what I am requiring.)

Upvotes: 0

Views: 823

Answers (3)

Il Vic
Il Vic

Reputation: 5666

You can use Undo e Redo Application Commands. This is the MVVM not compliant version:

In your XAML

<TextBox Margin="5" PreviewKeyUp="TextBox_PreviewKeyUp" AcceptsReturn="False" />

In your code-behind

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;
    }
}

I hope this is the functionality you meant.

Upvotes: 1

Claudio P
Claudio P

Reputation: 2203

You could simply use the PreviewKeyDown event and check for Key.Down or Key.Up and read a List of your last commands. If you set e.Handled = true the cursor don't jump up.

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
}

To make it MVVM-compliant you can use an eventtrigger which triggers a command in your Viewmodel. Hope this gives you the idea. Unfortunately I haven't enough time to program for you. :)

Upvotes: 1

mike00
mike00

Reputation: 448

You can persist commands into stack collection.

Upvotes: -1

Related Questions