Per Svensson
Per Svensson

Reputation: 744

WPF MVVM Databinding - Check for space and then clear the checkbox

im kind of new to using the MVVM patter on my WPF application and i have stumbled into a strange situation. Im actually trying to make something similar to the Metainputtextbox here on StackOverflow (when your writing a new question).

So what im trying to do:

I have a textbox (doh!) and binding it to a property in my viewModel. On the set property im checking for a space (' ') if there is a space but its not empty (meaning there is a metaword in there) i trim it from spaces and saves it to my private property. And calls the updateProp. Now here comes the tricky part. After the metaword is saved i want to clear the string and textbox but setting my property to "" will of course trigger the whole thing around again.

XAML

<TextBox 
         Name="txtBoxMetaInput" 
         Text="{Binding Path=MetaInput, Mode=TwoWay,
         UpdateSourceTrigger=PropertyChanged}"/>

viewModel

    private string metaInput { get; set; }
    public string MetaInput 
    {
        get {  return metaInput; }
        set 
        {
            if (value.Contains(' ') && String.IsNullOrEmpty(value) == false)
            {
                metaInput = value.Trim(' ');
                saveTheMetaKeyWordToAnArrayOfMetawords();
                this.OnPropertyChanged("MetaInput");
            }
        }
    }

Now whats missing there is that i want to empty the textbox and clear the property´s after saving it to the metaword array.

This problem probably just needs a new set of eyes on it :)

Upvotes: 1

Views: 1113

Answers (2)

bruceboughton
bruceboughton

Reputation: 642

The best solution is probably to use a value converter on the binding that converts from string to string[] and back again:

<local:TagConverter x:Key="TagConverter" />

<TextBox 
      Name="txtBoxMetaInput" 
      Text="{Binding Path=MetaInput, Mode=TwoWay,
      UpdateSourceTrigger=PropertyChanged, Converter={StaticResource TagConverter}}"/>

TagConverter is a class you write which implements IValueConverter. In Convert you convert from string to string[], splitting on spaces. In ConvertBack, you join the string[] back to a string.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564641

Now here comes the tricky part. After the metaword is saved i want to clear the string and textbox but setting my property to "" will of course trigger the whole thing around again.

Just set the backing field (before raising PropertyChanged), not the property. This will prevent the "retrigger" of the value.

Upvotes: 1

Related Questions