views:

604

answers:

3

Hi,

I am having a property of int type in my view model which is bound to a text box. Everything works properly, two way binding works fine except in one case -

If i clear the value of text box, property setter doesn't gets called and although value is cleared in text box, property still holds the previous value.

has anyone faced similar issue, is there any workaround for this?

Here is the property -

   public int MaxOccurrences
    {
        get
        {
            return this.maxOccurrences;
        }
        set
        {
            if (this.maxOccurrences != value)
            {
                this.maxOccurrences = value;
                base.RaisePropertyChanged("MaxOccurrences");
            }
        }
    }

Here is how I am binding the property in xaml -

<TextBox Text="{Binding Path=MaxOccurrences, Mode=TwoWay, 
    NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" 
    HorizontalAlignment="Center" Width="30" Margin="0,0,5,0"/>
+3  A: 

This is partially a guess (I haven't got VS handy right now to try it out), but I think it's because a cleared text box is an empty string (""), which can't be implicitly converted to an int. You should probably implemented a type converter to provide the conversion for you. (you probably want to do something like convert "" to 0)

Simon P Stevens
Easiest way to check -- run your project in Visual Studio and watch the Output window (View-Output). When you clear the textbox, you should see the Binding error Simon is talking about.
Tiberiu Ana
i have VS handy, and you're right. +1
Rob Fonseca-Ensor
Cheers rob.
Simon P Stevens
+1  A: 

It's because an int value can't be null. It's best to use a string property that converts the value for you within your code to the required int property field.

That way you can perform a

if(string.IsNullOrEmpty(text))
{
  this.intValue = 0;
}
ChrisBD
And the down vote for what reason?
ChrisBD
I don't see anything wrong with it. Have a +1 from me. Although I think the preferred way would be a type converter rather than a duplicate property.
Simon P Stevens
Thank you. I only asked in case I had missed something. Constructive criticism is always welcome as how else do we learn from our mistakes?
ChrisBD
+1  A: 

I had the similar problem.

You just need to update the code as:

<TextBox Text="{Binding Path=MaxOccurrences, Mode=TwoWay, TargetNullValue={x:Static sys:String.Empty},
NotifyOnSourceUpdated=True,  UpdateSourceTrigger=PropertyChanged}"  
HorizontalAlignment="Center" Width="30" Margin="0,0,5,0"/> 
WPF User