Change the text in a TextBox with Text = "{Binding SomeText}" so it is undoable

101 views Asked by At

I have a textbox that has text bound:

<TextBox x:Name="textBox" Text="{Binding SomeText}" />

Is there a way to change the text from code in a way so that it is undoable.

Only way I can think of is ClipBoard and textBox.Paste() but don't want to alter clipboard in case user has something there.

It is for a control that looks like this: enter image description here

The buttons changes the text and I want it to be undoable.

2

There are 2 answers

11
Andrew On BEST ANSWER

This works for me:

xaml:

<UserControl x:Class="TextboxButton.theControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Vertical">
    <TextBox x:Name="textBox"/>
    <Button Content="Push me to set textbox text" Click="Button_Click"/>
</StackPanel>

in the code-behind:

public partial class theControl : UserControl
{
    public theControl()
    {
        InitializeComponent();
    }

    public string TextToSet
    {
        get { return (string)GetValue(TextToSetProperty); }
        set { SetValue(TextToSetProperty, value); }
    }
    public static DependencyProperty TextToSetProperty = DependencyProperty.Register("TextToSet", typeof(string), typeof(MainWindow), null);

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        textBox.SelectAll();
        textBox.SelectedText = TextToSet;
    }
}

When using it, set the TextToSet property to whatever the button click should provide.

0
Johan Larsson On

When subclassing this is cleaner:

this.BeginChange();
this.SetCurrentValue(TextProperty, text);
this.EndChange();