Search code examples
c#wpftrimpropertychangedupdatesourcetrigger

Let user enter spaces between words but remove leading and trailing spaces when using PropertyChanged


In the following code, I'm doing a search as soon as the seventh character is entered. Everything is working fine except that the user cannot type spaces because, as expected they are getting removed every time a new character is entered since I'm calling the Trim() method on PropertyChangedevent. What I would like to be able to do is give the user the ability to type spaces but remove any leading and trailing spaces. In other words, if the user enters some spaces before and after the word or sentence he/she is searching for I want to remove the spaces and just search for the word.

For instance if the user types... <space><space><space>The Cat<space><space><space> I want the program to ignore the spaces and search for The Cat as soon as the last t is entered.

What would be the best way to accomplish this?

XAML:

<TextBox x:Name="myTextBox" Text="{Binding InputFileNameChanged, UpdateSourceTrigger=PropertyChanged}"/>

ViewModel .CS

    public string InputFileNameChanged
    {
        get { return _inputFileName; }
        set {
            _inputFileName = value.Trim();

            if (_inputFileName.Length == 7) {
                // search file
            }
        }
    }

Solution

  • If I were you, I'd not trim the backing field, and instead only trim before conducting the check/search. i.e.

    public string InputFileNameChanged
    {
        get { return _inputFileName; }
        set {
            _inputFileName = value;
            var trimmed = value.Trim();
            if (trimmed.Length >= 7) {
                // search file using trimmed
            }
        }
    }