禁用特殊字符(" /: ?)有什么可重复使用,但简单有效的方法?“;& lt;比;")在WPF文本

本文关键字:quot 简单 方法 有效 文本 WPF lt 特殊字符 什么 | 更新日期: 2023-09-27 18:08:38

我的应用程序中有几个WPF文本框,它们将用于指定文件名。我正在寻找一个解决方案,将快速和容易地让我不允许特殊字符(即。'/: ?"& lt;

禁用特殊字符(" /: ?)有什么可重复使用,但简单有效的方法?“;& lt;比;")在WPF文本

我创建了一个名为"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中的任何文本框中,像这样:

<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>