Reputation: 17580
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:
The buttons changes the text and I want it to be undoable.
Upvotes: 0
Views: 93
Reputation: 17580
When subclassing this is cleaner:
this.BeginChange();
this.SetCurrentValue(TextProperty, text);
this.EndChange();
Upvotes: 1
Reputation: 1492
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.
Upvotes: 1