When using textbox.Undo(); I get the following error:
Cannot Undo or Redo while undo unit is open.
Now I understand why this is
Instead of using Undo and TextChanged, you should use the PreviewTextInput
and DataObject.Pasting
events. In the PreviewTextInput
event handler, set e.Handled
to true if the typed text is an invalid character. In the Pasting
event handler, call e.CancelCommand()
if the pasted text is invalid.
Here is an example for a text box that accepts only the digits 0 and 1:
XAML:
Code behind:
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
namespace BinaryTextBox
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void txtBinary_PreviewTextInput(object sender,
TextCompositionEventArgs e)
{
e.Handled = e.Text != "0" && e.Text != "1";
}
private void txtBinary_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (!Regex.IsMatch(e.DataObject.GetData(typeof(string)).ToString(), "^[01]+$"))
{
e.CancelCommand();
}
}
}
}