I have written a simple WPF application in which I wanted to test the Undo method provided by WPF TextBox. Basically on clicking the Undo button the value of TextBox has to be reverted.
This is my xaml code
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBox Name="textBox1" />
<Button Name="button1" Click="button1_Click">Undo</Button>
<Button Name="button2" Click="button2_Click">Change value to 100</Button>
</StackPanel>
</Window>
In my xaml.cs, I have written the following:
Case 1: Where Undo is working:: I click on “Change value to 100” button on the window, the TextBox’s text becomes 100. Now I click on Undo button the value of TextBox becomes empty.
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Undo();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "100";
}
}
Case 2: Where Undo is not working:: I set the value of TextBox’s text to 100 in constructor, the TextBox’s text becomes 100. Now I click on Undo button the value of TextBox doesn’t become empty !!
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
textBox1.Text = "100";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Undo();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
}
}
Why doesn’t the Undo functionality work in second case?
Is it because the TextBox is still not constructed ? But I checked all the properties of TextBox like Loaded, Initialized , etc which were all set to “True”
I’m not sure of the technical reason, but many controls in WPF won’t be fully functional until after the constructor. But you can still work around this by hooking the Loaded event.
The Undo button should work properly then.