Skip to main content
 首页 » 编程设计

|") 的可重用但简单有效的方法是什么" rel="bookmark">c#之在 WPF TextBox 中禁止特殊字符 ("\/: " > |") 的可重用但简单有效的方法是什么

2024年02月06日16findumars

我的应用程序中有几个 WPF 文本框,它们将用于指定文件名。我正在寻找一种解决方案,它可以快速轻松地禁止将特殊字符(即“\/: ?” < > |)输入这些文本框,而无需创建继承自 TextBox 和不需要使用正则表达式。

请您参考如下方法:

我创建了一个名为“DisallowSpecialCharatersTextBoxBehavior”的静态类,它利用了 WPF 中可附加属性的强大功能,如下所示:

public static class DisallowSpecialCharactersTextboxBehavior 
{ 
    public static DependencyProperty DisallowSpecialCharactersProperty = 
        DependencyProperty.RegisterAttached("DisallowSpecialCharacters", typeof(bool), typeof(DisallowSpecialCharactersTextboxBehavior), new PropertyMetadata(DisallowSpecialCharactersChanged)); 
 
    public static void SetDisallowSpecialCharacters(TextBox textBox, bool disallow) 
    { 
        textBox.SetValue(DisallowSpecialCharactersProperty, disallow); 
    } 
 
    public static bool GetDisallowSpecialCharacters(TextBox textBox) 
    { 
        return (bool)textBox.GetValue(DisallowSpecialCharactersProperty); 
    } 
 
    private static void DisallowSpecialCharactersChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 
    { 
        var tb = dependencyObject as TextBox; 
        if (tb != null) 
        { 
 
            if ((bool)e.NewValue) 
            { 
                tb.PreviewTextInput += tb_PreviewTextInput; 
                tb.AddHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler(tb_Pasting)); 
            } 
            else 
            { 
                tb.PreviewTextInput -= tb_PreviewTextInput; 
                tb.RemoveHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler(tb_Pasting)); 
            } 
 
        } 
    } 
 
    private static void tb_Pasting(object sender, DataObjectPastingEventArgs e) 
    { 
        var pastedText = e.DataObject.GetData(typeof(string)) as string; 
 
        Path.GetInvalidFileNameChars().ToList().ForEach(c => 
            { 
                if (pastedText.Contains(c)) 
                { 
                    e.CancelCommand(); 
                } 
 
            }); 
    } 
 
    private static void tb_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) 
    { 
        if (Path.GetInvalidFileNameChars().ToList().ConvertAll(x => x.ToString()).Contains(e.Text)) 
        { 
            e.Handled = true; 
        } 
 
    } 
} 

它可以很容易地应用于 WPF 中的任何 TextBox,如下所示:

<Window x:Class="ExampleApp.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:ExampleApp" 
        Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
        <TextBox local:DisallowSpecialCharactersTextboxBehavior.DisallowSpecialCharacters="true"  /> 
    </Grid> 
</Window>