HTML如何禁止文本框输入

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTML如何禁止文本框输入相关的知识,希望对你有一定的参考价值。

两种方法:1、<input type="text" name="noedit" size="20" disabled="disabled" value="不可编辑">,这种方法可以让文本框不可编辑,但同时会导致服务端不能获取该文本框的值。2、<input type="text" name="noedit" size="20" readonly="readonly" value="不可输入">,这种方法可让文本框不可输入,但服务端可以获取该文本框的值。是什么需求就怎么用吧。 参考技术A

禁止文本框输入有以下两种方法:

    设置input为只读状态,代码如下:

<input readonly="readonly" value="test1"/>

2.设置input为不用状态,代码如下:

<input disabled="disabled" value="test2"/>

html文本域两种样式:

    没有滚动条的文本域(无边框);

<textarea   style="border:   0;   overflow:   auto;   color:   #FFFFFF;   background-image:   url(http://expert.csdn.net/images/csdn.gif)"></textarea>

2.红色边框的文本域;

<textarea   style="border:   #FF0000   1px   solid;   overflow:   visible;   color:   #FFFFFF;   background-image:   url(http://expert.csdn.net/images/csdn.gif)"></textarea>

参考资料

html中的input文本框禁止输入问题.CSDN[引用时间2018-1-5]

参考技术B <!--三种方案都可以!-->
<input type="text" name="自定义" readonly="readonly" />
<input type="text" name="自定义" disabled="disabled" /> 
<input type="text" name="自定义" autocomplete="off" id="number"/>

参考技术C 文本框里设置readonly属性 readonly="readonly" 参考技术D <input type="text" name="T1" size="20" readonly value="11">

如何定义文本框输入限制?

【中文标题】如何定义文本框输入限制?【英文标题】:How to define TextBox input restrictions? 【发布时间】:2010-11-09 09:06:49 【问题描述】:

如何限制 TextBox 只接受大写字母,例如数字,或禁止输入任何特殊字符?

当然,在此处捕获 TextInput 事件并处理文本是小菜一碟,但这样做是否正确?

【问题讨论】:

【参考方案1】:

我过去曾通过附加行为完成此操作,可以这样使用:

<TextBox b:Masking.Mask="^\pLu*$"/>

附加的行为代码如下所示:

/// <summary>
/// Provides masking behavior for any <see cref="TextBox"/>.
/// </summary>
public static class Masking

    private static readonly DependencyPropertyKey _maskExpressionPropertyKey = DependencyProperty.RegisterAttachedReadOnly("MaskExpression",
        typeof(Regex),
        typeof(Masking),
        new FrameworkPropertyMetadata());

    /// <summary>
    /// Identifies the <see cref="Mask"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty MaskProperty = DependencyProperty.RegisterAttached("Mask",
        typeof(string),
        typeof(Masking),
        new FrameworkPropertyMetadata(OnMaskChanged));

    /// <summary>
    /// Identifies the <see cref="MaskExpression"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty MaskExpressionProperty = _maskExpressionPropertyKey.DependencyProperty;

    /// <summary>
    /// Gets the mask for a given <see cref="TextBox"/>.
    /// </summary>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask is to be retrieved.
    /// </param>
    /// <returns>
    /// The mask, or <see langword="null"/> if no mask has been set.
    /// </returns>
    public static string GetMask(TextBox textBox)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        return textBox.GetValue(MaskProperty) as string;
    

    /// <summary>
    /// Sets the mask for a given <see cref="TextBox"/>.
    /// </summary>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask is to be set.
    /// </param>
    /// <param name="mask">
    /// The mask to set, or <see langword="null"/> to remove any existing mask from <paramref name="textBox"/>.
    /// </param>
    public static void SetMask(TextBox textBox, string mask)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        textBox.SetValue(MaskProperty, mask);
    

    /// <summary>
    /// Gets the mask expression for the <see cref="TextBox"/>.
    /// </summary>
    /// <remarks>
    /// This method can be used to retrieve the actual <see cref="Regex"/> instance created as a result of setting the mask on a <see cref="TextBox"/>.
    /// </remarks>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask expression is to be retrieved.
    /// </param>
    /// <returns>
    /// The mask expression as an instance of <see cref="Regex"/>, or <see langword="null"/> if no mask has been applied to <paramref name="textBox"/>.
    /// </returns>
    public static Regex GetMaskExpression(TextBox textBox)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
         

        return textBox.GetValue(MaskExpressionProperty) as Regex;
    

    private static void SetMaskExpression(TextBox textBox, Regex regex)
    
        textBox.SetValue(_maskExpressionPropertyKey, regex);
    

    private static void OnMaskChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    
        var textBox = dependencyObject as TextBox;
        var mask = e.NewValue as string;
        textBox.PreviewTextInput -= textBox_PreviewTextInput;
        textBox.PreviewKeyDown -= textBox_PreviewKeyDown;
        DataObject.RemovePastingHandler(textBox, Pasting);

        if (mask == null)
        
            textBox.ClearValue(MaskProperty);
            textBox.ClearValue(MaskExpressionProperty);
        
        else
        
            textBox.SetValue(MaskProperty, mask);
            SetMaskExpression(textBox, new Regex(mask, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace));
            textBox.PreviewTextInput += textBox_PreviewTextInput;
            textBox.PreviewKeyDown += textBox_PreviewKeyDown;
            DataObject.AddPastingHandler(textBox, Pasting);
        
    

    private static void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        if (maskExpression == null)
        
            return;
        

        var proposedText = GetProposedText(textBox, e.Text);

        if (!maskExpression.IsMatch(proposedText))
        
            e.Handled = true;
        
    

    private static void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        if (maskExpression == null)
        
            return;
        

        //pressing space doesn't raise PreviewTextInput - no idea why, but we need to handle
        //explicitly here
        if (e.Key == Key.Space)
        
            var proposedText = GetProposedText(textBox, " ");

            if (!maskExpression.IsMatch(proposedText))
            
                e.Handled = true;
            
        
    

    private static void Pasting(object sender, DataObjectPastingEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        if (maskExpression == null)
        
            return;
        

        if (e.DataObject.GetDataPresent(typeof(string)))
        
            var pastedText = e.DataObject.GetData(typeof(string)) as string;
            var proposedText = GetProposedText(textBox, pastedText);

            if (!maskExpression.IsMatch(proposedText))
            
                e.CancelCommand();
            
        
        else
        
            e.CancelCommand();
        
    

    private static string GetProposedText(TextBox textBox, string newText)
    
        var text = textBox.Text;

        if (textBox.SelectionStart != -1)
        
            text = text.Remove(textBox.SelectionStart, textBox.SelectionLength);
        

        text = text.Insert(textBox.CaretIndex, newText);

        return text;
    

【讨论】:

我不会这么说的。我确实写它比你需要的灵活得多。随意采用这个概念并根据您的需要进行简化。 非常好,肯特。一种灵活而强大的解决方案,用于限制 TextBox 中的条目。 +1 优雅!希望我能给超过+1 @Agzam,唯一困难的部分是学习 RegEx 而不会感到眼球疼痛......以及复制和粘贴...... @Andres: Masking.SetMask(textBox, "^pLu*$");【参考方案2】:

我还改进了 Kent Boogaart 的回答,还处理了以前可能导致违反模式的以下操作:

退格键 以可能违反模式的方式选择和拖动文本 剪切命令

例如,Kent Boogaart 的回答允许用户输入“ac”,首先输入“abc”,然后用退格键删除“b”,这违反了以下正则表达式

^(a|ab|abc)$

用法(不变):

&lt;TextBox b:Masking.Mask="^\pLu*$"/&gt;

面具类:

public static class Masking

    private static readonly DependencyPropertyKey _maskExpressionPropertyKey = DependencyProperty.RegisterAttachedReadOnly("MaskExpression",
            typeof(Regex),
            typeof(Masking),
            new FrameworkPropertyMetadata());

    /// <summary>
    /// Identifies the <see cref="Mask"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty MaskProperty = DependencyProperty.RegisterAttached("Mask",
            typeof(string),
            typeof(Masking),
            new FrameworkPropertyMetadata(OnMaskChanged));

    /// <summary>
    /// Identifies the <see cref="MaskExpression"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty MaskExpressionProperty = _maskExpressionPropertyKey.DependencyProperty;

    /// <summary>
    /// Gets the mask for a given <see cref="TextBox"/>.
    /// </summary>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask is to be retrieved.
    /// </param>
    /// <returns>
    /// The mask, or <see langword="null"/> if no mask has been set.
    /// </returns>
    public static string GetMask(TextBox textBox)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        return textBox.GetValue(MaskProperty) as string;
    

    /// <summary>
    /// Sets the mask for a given <see cref="TextBox"/>.
    /// </summary>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask is to be set.
    /// </param>
    /// <param name="mask">
    /// The mask to set, or <see langword="null"/> to remove any existing mask from <paramref name="textBox"/>.
    /// </param>
    public static void SetMask(TextBox textBox, string mask)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        textBox.SetValue(MaskProperty, mask);
    

    /// <summary>
    /// Gets the mask expression for the <see cref="TextBox"/>.
    /// </summary>
    /// <remarks>
    /// This method can be used to retrieve the actual <see cref="Regex"/> instance created as a result of setting the mask on a <see cref="TextBox"/>.
    /// </remarks>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask expression is to be retrieved.
    /// </param>
    /// <returns>
    /// The mask expression as an instance of <see cref="Regex"/>, or <see langword="null"/> if no mask has been applied to <paramref name="textBox"/>.
    /// </returns>
    public static Regex GetMaskExpression(TextBox textBox)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        return textBox.GetValue(MaskExpressionProperty) as Regex;
    

    private static void SetMaskExpression(TextBox textBox, Regex regex)
    
        textBox.SetValue(_maskExpressionPropertyKey, regex);
    

    private static void OnMaskChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    
        var textBox = dependencyObject as TextBox;
        var mask = e.NewValue as string;
        textBox.PreviewTextInput -= textBox_PreviewTextInput;
        textBox.PreviewKeyDown -= textBox_PreviewKeyDown;
        DataObject.RemovePastingHandler(textBox, Pasting);
        DataObject.RemoveCopyingHandler(textBox, NoDragCopy);
        CommandManager.RemovePreviewExecutedHandler(textBox, NoCutting);


        if (mask == null)
        
            textBox.ClearValue(MaskProperty);
            textBox.ClearValue(MaskExpressionProperty);
        
        else
        
            textBox.SetValue(MaskProperty, mask);
            SetMaskExpression(textBox, new Regex(mask, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace));
            textBox.PreviewTextInput += textBox_PreviewTextInput;
            textBox.PreviewKeyDown += textBox_PreviewKeyDown;
            DataObject.AddPastingHandler(textBox, Pasting);
            DataObject.AddCopyingHandler(textBox, NoDragCopy);
            CommandManager.AddPreviewExecutedHandler(textBox, NoCutting);
        
    

    private static void NoCutting(object sender, ExecutedRoutedEventArgs e)
    
        if(e.Command == ApplicationCommands.Cut)
        
            e.Handled = true;
        
    

    private static void NoDragCopy(object sender, DataObjectCopyingEventArgs e)
    
        if (e.IsDragDrop)
        
            e.CancelCommand();
        
    

    private static void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        if (maskExpression == null)
        
            return;
        

        var proposedText = GetProposedText(textBox, e.Text);

        if (!maskExpression.IsMatch(proposedText))
        
            e.Handled = true;
        
    

    private static void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        if (maskExpression == null)
        
            return;
        

        string proposedText = null;

        //pressing space doesn't raise PreviewTextInput, reasons here http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/446ec083-04c8-43f2-89dc-1e2521a31f6b?prof=required
        if (e.Key == Key.Space)
        
            proposedText = GetProposedText(textBox, " ");
        
        // Same story with backspace
        else if(e.Key == Key.Back)
        
            proposedText = GetProposedTextBackspace(textBox);
        

        if (proposedText != null && proposedText != string.Empty && !maskExpression.IsMatch(proposedText))
        
            e.Handled = true;
        

    

    private static void Pasting(object sender, DataObjectPastingEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        if (maskExpression == null)
        
            return;
        

        if (e.DataObject.GetDataPresent(typeof(string)))
        
            var pastedText = e.DataObject.GetData(typeof(string)) as string;
            var proposedText = GetProposedText(textBox, pastedText);

            if (!maskExpression.IsMatch(proposedText))
            
                e.CancelCommand();
            
        
        else
        
            e.CancelCommand();
        
    

    private static string GetProposedTextBackspace(TextBox textBox)
    
        var text = GetTextWithSelectionRemoved(textBox);
        if (textBox.SelectionStart > 0 && textBox.SelectionLength == 0)
        
            text = text.Remove(textBox.SelectionStart-1, 1);
        

        return text;
    


    private static string GetProposedText(TextBox textBox, string newText)
    
        var text = GetTextWithSelectionRemoved(textBox);
        text = text.Insert(textBox.CaretIndex, newText);

        return text;
    

    private static string GetTextWithSelectionRemoved(TextBox textBox)
    
        var text = textBox.Text;

        if (textBox.SelectionStart != -1)
        
            text = text.Remove(textBox.SelectionStart, textBox.SelectionLength);
        
        return text;
    

【讨论】:

您通过 3 种方式改进了解决方案,但阅读其简短说明并没有敲响警钟。我认为这与在 TextBox 中复制粘贴文本有关,但 Kent 的解决方案已经阻止了错误文本。您能否解释一下改进阻止了哪些用例?谢谢 这些改进可以防止用户违反正则表达式规则。因此,例如,在这些更改之前,您可以使用 Backspace 使规则变为非法。所以如果模式是^123$,你可以输入123,然后删除2,它会让你。现在没有了。其他改进也是如此 - 剪切文本和拖动文本。 我现在明白你的意思了,但只有复制粘贴操作才能让用户到达文本框中开始出现“123”的位置。只输入字符“1”(或任何其他字符)是不可能的,因为它不会验证“^123$”。在字符串中的 typed 上使用退格键将始终尊重该模式,因为先前的输入已经过验证。一些用户肯定会复制粘贴,而您的改进将解决这种边缘情况,这在一段时间内一直是个谜。谢谢 "在输入的字符串上使用退格键将始终尊重模式,因为之前的输入已经过验证。"仅当光标位于文本框末尾时才如此。如果用户将它移到中间和退格,那么你就会遇到问题。 这是一个好主意,我花了一段时间来构建一个遇到此问题的正则表达式。诀窍是引入 optionality (将锚定作为验证 whole 事物所需的): ^a?(ab)?(abc)?$ 使用该正则表达式用户可以在 b 上退格并留下无效的 ac。您的改进解决了这个问题。【参考方案3】:

我更改了 VitalyB 的代码以支持颜色主题。如果它不符合 RegEx 脚本,它不会阻止用户输入,它只是突出显示文本框。文本框会是没有交互的主题默认,然后根据输入设置后的值默认为浅绿色或红色。您还可以通过以下方式以编程方式设置失败和通过颜色:

b:ColorMasking.PassColor = "Hexadecimal Value"
b:ColorMasking.FailColor = "Hexadecimal Value"

类如下:

public class ColorMasking : DependencyObject

    private static readonly DependencyPropertyKey _maskExpressionPropertyKey = DependencyProperty.RegisterAttachedReadOnly("MaskExpression",
            typeof(Regex),
            typeof(ColorMasking),
            new FrameworkPropertyMetadata());

    /// <summary>
    /// Identifies the <see cref="Mask"/> dependency property.
    /// </summary>
    /// 
    public static readonly DependencyProperty PassColorProperty = DependencyProperty.RegisterAttached("PassColor",
            typeof(string),
            typeof(ColorMasking),
            new PropertyMetadata("#99FF99"));

    public static void SetPassColor(DependencyObject obj, string passColor)
    
        obj.SetValue(PassColorProperty, passColor);
    

    public static string GetPassColor(DependencyObject obj)
    
        return (string)obj.GetValue(PassColorProperty);
    


    public static readonly DependencyProperty FailColorProperty = DependencyProperty.RegisterAttached("FailColor",
            typeof(string),
            typeof(ColorMasking),
            new PropertyMetadata("#FFCCFF"));

    public static void SetFailColor(DependencyObject obj, string failColor)
    
        obj.SetValue(FailColorProperty, failColor);
    

    public static string GetFailColor(DependencyObject obj)
    
        return (string)obj.GetValue(FailColorProperty);
    

    public static readonly DependencyProperty MaskProperty = DependencyProperty.RegisterAttached("Mask",
            typeof(string),
            typeof(ColorMasking),
            new FrameworkPropertyMetadata(OnMaskChanged));

    private static void OnPassColorChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    
        var textBox = dependencyObject as TextBox;
        var color = e.NewValue as string;
        textBox.SetValue(PassColorProperty, color);
    

    /// <summary>
    /// Identifies the <see cref="MaskExpression"/> dependency property.
    /// </summary>
    public static readonly DependencyProperty MaskExpressionProperty = _maskExpressionPropertyKey.DependencyProperty;

    /// <summary>
    /// Gets the mask for a given <see cref="TextBox"/>.
    /// </summary>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask is to be retrieved.
    /// </param>
    /// <returns>
    /// The mask, or <see langword="null"/> if no mask has been set.
    /// </returns>
    public static string GetMask(TextBox textBox)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        return textBox.GetValue(MaskProperty) as string;
    

    /// <summary>
    /// Sets the mask for a given <see cref="TextBox"/>.
    /// </summary>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask is to be set.
    /// </param>
    /// <param name="mask">
    /// The mask to set, or <see langword="null"/> to remove any existing mask from <paramref name="textBox"/>.
    /// </param>
    public static void SetMask(TextBox textBox, string mask)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        textBox.SetValue(MaskProperty, mask);
    

    /// <summary>
    /// Gets the mask expression for the <see cref="TextBox"/>.
    /// </summary>
    /// <remarks>
    /// This method can be used to retrieve the actual <see cref="Regex"/> instance created as a result of setting the mask on a <see cref="TextBox"/>.
    /// </remarks>
    /// <param name="textBox">
    /// The <see cref="TextBox"/> whose mask expression is to be retrieved.
    /// </param>
    /// <returns>
    /// The mask expression as an instance of <see cref="Regex"/>, or <see langword="null"/> if no mask has been applied to <paramref name="textBox"/>.
    /// </returns>
    public static Regex GetMaskExpression(TextBox textBox)
    
        if (textBox == null)
        
            throw new ArgumentNullException("textBox");
        

        return textBox.GetValue(MaskExpressionProperty) as Regex;
    

    private static void SetMaskExpression(TextBox textBox, Regex regex)
    
        textBox.SetValue(_maskExpressionPropertyKey, regex);
    

    private static void OnMaskChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    
        var textBox = dependencyObject as TextBox;
        var mask = e.NewValue as string;
        textBox.PreviewTextInput -= textBox_PreviewTextInput;
        textBox.PreviewKeyDown -= textBox_PreviewKeyDown;
        DataObject.RemovePastingHandler(textBox, Pasting);
        DataObject.RemoveCopyingHandler(textBox, NoDragCopy);
        CommandManager.RemovePreviewExecutedHandler(textBox, NoCutting);

        if (mask == null)
        
            textBox.ClearValue(MaskProperty);
            textBox.ClearValue(MaskExpressionProperty);
        
        else
        
            textBox.SetValue(MaskProperty, mask);
            SetMaskExpression(textBox, new Regex(mask, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace));
            textBox.PreviewTextInput += textBox_PreviewTextInput;
            textBox.PreviewKeyDown += textBox_PreviewKeyDown;
            DataObject.AddPastingHandler(textBox, Pasting);
            DataObject.AddCopyingHandler(textBox, NoDragCopy);
            CommandManager.AddPreviewExecutedHandler(textBox, NoCutting);
        
    

    private static void NoCutting(object sender, ExecutedRoutedEventArgs e)
    
        if (e.Command == ApplicationCommands.Cut)
        
            e.Handled = true;
        
    

    private static void NoDragCopy(object sender, DataObjectCopyingEventArgs e)
    
        if (e.IsDragDrop)
        
            e.CancelCommand();
        
    

    private static void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        string passHex = (string)textBox.GetValue(PassColorProperty);
        string failHex = (string)textBox.GetValue(FailColorProperty);
        Color passColor = Extensions.ToColorFromHex(passHex);
        Color failColor = Extensions.ToColorFromHex(failHex);

        if (maskExpression == null)
        
            return;
        

        var proposedText = GetProposedText(textBox, e.Text);

        if (!maskExpression.IsMatch(proposedText))
        
            textBox.Background = new SolidColorBrush(failColor);
        
        else
        
            textBox.Background = new SolidColorBrush(passColor);
        
    

    private static void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
    
        var textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        string passHex = (string)textBox.GetValue(PassColorProperty);
        string failHex = (string)textBox.GetValue(FailColorProperty);
        Color passColor = Extensions.ToColorFromHex(passHex);
        Color failColor = Extensions.ToColorFromHex(failHex);

        if (maskExpression == null)
        
            return;
        

        string proposedText = null;

        //pressing space doesn't raise PreviewTextInput, reasons here http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/446ec083-04c8-43f2-89dc-1e2521a31f6b?prof=required
        if (e.Key == Key.Space)
        
            proposedText = GetProposedText(textBox, " ");
        
        // Same story with backspace
        else if (e.Key == Key.Back)
        
            proposedText = GetProposedTextBackspace(textBox);
        

        if (proposedText != null && !maskExpression.IsMatch(proposedText))
        
            textBox.Background = new SolidColorBrush(failColor);
        
        else
        
            textBox.Background = new SolidColorBrush(passColor);
        

    

    private static void Pasting(object sender, DataObjectPastingEventArgs e)
    
        TextBox textBox = sender as TextBox;
        var maskExpression = GetMaskExpression(textBox);

        string passHex = (string)textBox.GetValue(PassColorProperty);
        string failHex = (string)textBox.GetValue(FailColorProperty);
        Color passColor = Extensions.ToColorFromHex(passHex);
        Color failColor = Extensions.ToColorFromHex(failHex);

        if (maskExpression == null)
        
            return;
        

        if (e.DataObject.GetDataPresent(typeof(string)))
        
            var pastedText = e.DataObject.GetData(typeof(string)) as string;
            var proposedText = GetProposedText(textBox, pastedText);

            if (!maskExpression.IsMatch(proposedText))
            
                textBox.Background = new SolidColorBrush(failColor);
            
            else
            
                textBox.Background = new SolidColorBrush(passColor);
            
        
        else
        
            textBox.Background = new SolidColorBrush(failColor);
        
    

    private static string GetProposedTextBackspace(TextBox textBox)
    
        var text = GetTextWithSelectionRemoved(textBox);
        if (textBox.SelectionStart > 0)
        
            text = text.Remove(textBox.SelectionStart - 1, 1);
        

        return text;
    


    private static string GetProposedText(TextBox textBox, string newText)
    
        var text = GetTextWithSelectionRemoved(textBox);
        text = text.Insert(textBox.CaretIndex, newText);

        return text;
    

    private static string GetTextWithSelectionRemoved(TextBox textBox)
    
        var text = textBox.Text;

        if (textBox.SelectionStart != -1)
        
            text = text.Remove(textBox.SelectionStart, textBox.SelectionLength);
        
        return text;
    

要运行,脚本需要 Aaron C 编写的类,此处解释:Silverlight/WPF sets ellipse with hexadecimal colour 此处显示:http://www.wiredprairie.us/blog/index.php/archives/659

如果网站被移动,代码如下:

public static class Extensions

    public static void SetFromHex(this Color c, string hex)
    
        Color c1 = ToColorFromHex(hex);

        c.A = c1.A;
        c.R = c1.R;
        c.G = c1.G;
        c.B = c1.B;
    

    public static Color ToColorFromHex(string hex)
    
        if (string.IsNullOrEmpty(hex))
        
            throw new ArgumentNullException("hex");
        

        // remove any "#" characters
        while (hex.StartsWith("#"))
        
            hex = hex.Substring(1);
        

        int num = 0;
        // get the number out of the string
        if (!Int32.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out num))
        
            throw new ArgumentException("Color not in a recognized Hex format.");
        

        int[] pieces = new int[4];
        if (hex.Length > 7)
        
            pieces[0] = ((num >> 24) & 0x000000ff);
            pieces[1] = ((num >> 16) & 0x000000ff);
            pieces[2] = ((num >> 8) & 0x000000ff);
            pieces[3] = (num & 0x000000ff);
        
        else if (hex.Length > 5)
        
            pieces[0] = 255;
            pieces[1] = ((num >> 16) & 0x000000ff);
            pieces[2] = ((num >> 8) & 0x000000ff);
            pieces[3] = (num & 0x000000ff);
        
        else if (hex.Length == 3)
        
            pieces[0] = 255;
            pieces[1] = ((num >> 8) & 0x0000000f);
            pieces[1] += pieces[1] * 16;
            pieces[2] = ((num >> 4) & 0x000000f);
            pieces[2] += pieces[2] * 16;
            pieces[3] = (num & 0x000000f);
            pieces[3] += pieces[3] * 16;
        
        return Color.FromArgb((byte)pieces[0], (byte)pieces[1], (byte)pieces[2], (byte)pieces[3]);
    


【讨论】:

【参考方案4】:
private void TextBox1_SelectionChanged(object sender, RoutedEventArgs e)

    string txt = TextBox1.Text;
    if (txt != "")
    
        TextBox1.Text = Regex.Replace(TextBox1.Text, "[^0-9]", "");
        if (txt != TextBox1.Text)
        
            TextBox1.Select(TextBox1.Text.Length, 0);
        
    

【讨论】:

我不知道如何使它成为自定义属性,但它是一个简单的解决方案。如果有人能像肯特那样将其转换为财产,我将不胜感激。【参考方案5】:

这里是现有解决方案的另一个版本。这是一个模拟“TextChanging”事件的行为,提供旧文本、新文本和取消更改的标志。这样我们就可以实现我们想要的任何过滤器。

我摆脱了仅用于空格字符的“PreviewKeyDown”处理程序。 TextBox 似乎使用路由命令来管理所有内容,并且“Space”确实有自己的命令,尽管它不是公开的。我还添加了对其他键盘快捷键的支持,例如“Ctrl+Backspace”(删除前一个单词)。

public class TextChangingBehavior : Behavior<TextBox>

    public event EventHandler<TextChangingEventArgs> TextChanging;

    protected override void OnAttached()
    
        base.OnAttached();

        AssociatedObject.PreviewTextInput += OnPreviewTextInput;
        CommandManager.AddPreviewExecutedHandler(AssociatedObject, OnPreviewExecutedHandler);
        DataObject.AddCopyingHandler(AssociatedObject, OnCopying);
        DataObject.AddPastingHandler(AssociatedObject, OnPasting);
    

    protected override void OnDetaching()
    
        base.OnDetaching();

        AssociatedObject.PreviewTextInput -= OnPreviewTextInput;
        CommandManager.RemovePreviewExecutedHandler(AssociatedObject, OnPreviewExecutedHandler);
        DataObject.RemoveCopyingHandler(AssociatedObject, OnCopying);
        DataObject.RemovePastingHandler(AssociatedObject, OnPasting);
    

    #region Text

    private enum CharCategory
    
        LetterOrDigit,
        Whitespace,
        Other
    

    private CharCategory GetCharCategory(char c)
    
        if (char.IsLetterOrDigit(c))
            return CharCategory.LetterOrDigit;
        else if (char.IsWhiteSpace(c))
            return CharCategory.Whitespace;
        else
            return CharCategory.Other;
    

    private string GetText(string input = null)
    
        var box = AssociatedObject;
        var text = box.Text ?? string.Empty;
        if (input != null)
        
            // Delete selection
            var deleteCount = box.SelectionLength;
            if (deleteCount > 0)
                text = text.Remove(box.SelectionStart, deleteCount);
            // Insert input
            if (input.Length > 0)
                text = text.Insert(box.CaretIndex, input);
        
        return text;
    

    #endregion

    private void OnPreviewExecutedHandler(object sender, ExecutedRoutedEventArgs e)
    
        var box = AssociatedObject;
        var selectionExists = box.SelectionLength > 0;
        var caretIndex = box.CaretIndex;
        string newText = null;

        if (e.Command == ApplicationCommands.Cut)
        
            if (selectionExists)
                newText = GetText(string.Empty);
        
        else if (e.Command == EditingCommands.Backspace)
        
            if (selectionExists)
                newText = GetText(string.Empty);
            else if (caretIndex > 0)
                newText = GetText().Remove(caretIndex - 1, 1);
        
        else if (e.Command == EditingCommands.Delete)
        
            if (selectionExists)
                newText = GetText(string.Empty);
            else
            
                newText = GetText();
                if (caretIndex >= newText.Length)
                    newText = null;
                else
                    newText = newText.Remove(caretIndex, 1);
            
        
        else if (e.Command == EditingCommands.DeletePreviousWord)
        
            if (selectionExists)
                newText = GetText(string.Empty);
            else if (caretIndex > 0)
            
                newText = GetText();
                var startIndex = caretIndex;
                // Include whitespaces
                do
                    startIndex--;
                while (startIndex > 0 && char.IsWhiteSpace(newText[startIndex]));
                // Include the next block
                var currentCategory = GetCharCategory(newText[startIndex]);
                while (startIndex > 0 && GetCharCategory(newText[startIndex - 1]) == currentCategory)
                    startIndex--;

                newText = newText.Remove(startIndex, caretIndex - startIndex);
            
        
        else if (e.Command == EditingCommands.DeleteNextWord)
        
            if (selectionExists)
                newText = GetText(string.Empty);
            else
            
                newText = GetText();
                if (caretIndex >= newText.Length)
                    newText = null;
                else
                
                    var endIndex = caretIndex + 1;
                    // Include the current block
                    var currentCategory = GetCharCategory(newText[caretIndex]);
                    while (endIndex < newText.Length && GetCharCategory(newText[endIndex]) == currentCategory)
                        endIndex++;
                    // Include whitespaces
                    while (endIndex < newText.Length && char.IsWhiteSpace(newText[endIndex]))
                        endIndex++;

                    newText = newText.Remove(caretIndex, endIndex - caretIndex);
                
            
        
        else if (e.Command is RoutedUICommand cmd && new[]  "Space", "ShiftSpace" .Contains(cmd.Name))
        
            newText = GetText(" ");
        

        if (newText != null && OnProcessChange(newText))
            e.Handled = true;
    

    private void OnCopying(object sender, DataObjectCopyingEventArgs e)
    
        if (e.IsDragDrop)
        
            if (OnProcessChange(GetText(string.Empty)))
                e.CancelCommand();
        
    

    private void OnPasting(object sender, DataObjectPastingEventArgs e)
    
        if (e.DataObject.GetDataPresent(typeof(string)))
        
            if (OnProcessChange(GetText((string)e.DataObject.GetData(typeof(string)))))
                e.CancelCommand();
        
    

    private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    
        if (!string.IsNullOrEmpty(e.Text))
        
            if (OnProcessChange(GetText(e.Text)))
                e.Handled = true;
        
    

    private bool OnProcessChange(string newValue)
    
        var oldValue = GetText();

        if (string.Equals(oldValue, newValue, StringComparison.Ordinal))
            return false;
        else
        
            var args = new TextChangingEventArgs(oldValue, newValue);
            OnTextChanging(args);
            return args.Cancel;
        
    

    protected virtual void OnTextChanging(TextChangingEventArgs e)
    
        TextChanging?.Invoke(this, e);
    


public class TextChangingEventArgs : EventArgs

    public string OldValue  get; 

    public string NewValue  get; 

    public bool Cancel  get; set; 

    public TextChangingEventArgs(string oldValue, string newValue)
    
        OldValue = oldValue;
        NewValue = newValue;
    

【讨论】:

正是我想要的。只想添加 Microsoft.Xaml.Behaviors.Wpf nuget 包才能使其正常工作。【参考方案6】:

另一种可能的解决方案是使用 Winforms 中的“MaskedTextBox”使用的“MaskedTextProvider”类使用“Masked TextBox”wpf 实现之一。

这里有两种可能的解决方案 -> https://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox 和这里 -> http://marlongrech.wordpress.com/2007/10/28/masked-textbox/

【讨论】:

以上是关于HTML如何禁止文本框输入的主要内容,如果未能解决你的问题,请参考以下文章

javascript怎么禁止在文本框中输入?

VB禁止文本框输入

javascript怎么禁止在文本框中输入?

C#限制文本框输入

如何在C#中,文本框不能粘贴功能

input 文本框禁止输入表情