创建用下划线替换空格的 WPF TextBox 的最佳方法是什么?

Gre*_*g D 3 c# wpf textbox wpf-controls

我正在FilteredTextBoxWPF 中创建一个子类化包含的TextBox控件。该FilteredTextBox范围内必须只允许字符[a-zA-Z0-9_]来输入,我已经得到了部分相当多的工作。我已经开始OnPreviewTextInput处理键入的字符,OnPreviewDrop过滤拖放的字符,并且我添加了一个 PreviewExecutedHandler,只要在控件上执行命令来处理粘贴,它就会运行。

到现在为止还挺好。

棘手的部分是控件还应该在输入时用下划线替换空格。

我想出了一个解决方案,但感觉很糟糕,我不知道它缺少什么。我觉得必须有一种我不知道的更好的技术。我所做的:

internal class FilteredTextBox : TextBox
{
    public FilteredTextBox()
    {
        CommandManager.AddPreviewExecutedHandler(this, this.HandlePreviewExecuteHandler);
    }

    private void HandlePreviewExecuteHandler(object sender, ExecutedRoutedEventArgs e)
    {
        var uiCmd = e.Command as RoutedUICommand;
        if (uiCmd != null && (uiCmd.Text == "Space" || uiCmd.Text == "ShiftSpace"))
        {
            // We're manually handling spaces, so we need to make appropriate checks.
            if (this.Text.Length == this.MaxLength) return;

            if (this.SelectionLength == 0)
            {
                // If the user is just typing a space normally
                // We need to cache CaretIndex b/c it's reset to 0 when we set Text.
                var tmpIndex = this.CaretIndex;
                this.Text = this.Text.Insert(tmpIndex, "_");
                this.CaretIndex = tmpIndex + 1;
            }
            else
            {
                // Otherwise, replace the selected text with the underscore and fixup the caret.
                this.SelectedText = "_";
                this.CaretIndex += this.SelectedText.Length;
                this.SelectionLength = 0;
            }

            e.Handled = true; // If someone hits the spacebar, say we handled it.
            return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更聪明的方法?

buf*_*erz 5

我会将 the 绑定TextBoxValueConverter按需消除空格并用下划线替换它们的 a 。

ValueConverter 看起来像这样:

public class SpaceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToString(value); 
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string text = System.Convert.ToString(value);

            //the meat and potatoes is this line
            text = text.Replace(" ", "_");    

            return text;
        }
    }
Run Code Online (Sandbox Code Playgroud)

TextBox会以这种方式绑定它:

<TextBox Text="{Binding Path=UserString, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource SpaceConverter}}" />
Run Code Online (Sandbox Code Playgroud)

请注意,UserString必须在当前DataContext.

不要忘记SpaceConverter在 XAML 中进行定义。假设您正在处理 a UserControl,一种方法是:

<UserControl.Resources>
   <local:SpaceConverter x:Key="SpaceConverter" />
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)

其中local定义为包含 SpaceConverter.cs 的命名空间。