Unable to use Undo in TextChanged

后端 未结 3 528
心在旅途
心在旅途 2021-01-04 14:34

When using textbox.Undo(); I get the following error:

Cannot Undo or Redo while undo unit is open.

Now I understand why this is

3条回答
  •  悲哀的现实
    2021-01-04 14:50

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

提交回复
热议问题