无法在TextChanged中使用撤消 [英] Unable to use Undo in TextChanged

查看:74
本文介绍了无法在TextChanged中使用撤消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用textbox.Undo();时我收到以下错误:

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

打开撤消单元时无法撤消或重做.

Cannot Undo or Redo while undo unit is open.

现在我理解为什么会这样(因为这是一个活动的可撤消事件),但是如果用户键入了无效字符,我可以通过哪个事件对文本框进行验证并撤消更改?

Now I understand why this is the case (because it is an active undoable event) but through what event can I perform validation on a text box and undo the change if the user has typed an invalid character?

推荐答案

应该使用 PreviewTextInput DataObject.Pasting 事件,而不是使用Undo和TextChanged.在 PreviewTextInput 事件处理程序中,如果键入的文本是无效字符,请将 e.Handled 设置为true.如果粘贴的文本无效,则在 Pasting 事件处理程序中,调用 e.CancelCommand().

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.

下面是一个仅接受数字0和1的文本框的示例.

Here is an example for a text box that accepts only the digits 0 and 1:

XAML:

<Window x:Class="BinaryTextBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="133" Width="329">
    <StackPanel>
        <TextBox x:Name="txtBinary" Width="100" Height="24"
                 PreviewTextInput="txtBinary_PreviewTextInput"
                 DataObject.Pasting="txtBinary_Pasting"/>
    </StackPanel>
</Window>

后面的代码:

using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;

namespace BinaryTextBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    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();
            }
        }
    }
}

这篇关于无法在TextChanged中使用撤消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆