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

标签 c# wpf file path dependency-properties

我的应用程序中有几个 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>

关于c# - 在 WPF TextBox 中禁止特殊字符 ("\/: ? "< > |") 的可重用但简单有效的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213964/

相关文章:

c# - 使用 InvokeCommandAction 传递 Source 和 Property,而不使用 MultiBindings

java - NULL值将文件加载到mysql表中

file - TCL:无法使用 "exec"命令打开程序

c# - 检查数据表中是否存在行?

c# - .net core azure WebJob 3.0.3 UseTimers 丢失

c# - 从JavaScript设置runat =“server”

wpf - 需要有关在一个 Visual Studio 解决方案中组织两个 WPF 应用程序的建议

wpf - 如何将控件的样式与当前主题匹配? (WPF)

c# - Foo<T> 其中 T 是接口(interface)或实现

visual-studio - Visual Studio 2008 自动恢复目录位置更改