Search code examples
c#.netwpfxamldata-binding

WPF binding not working properly with properties of int type


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

If I clear the value of TextBox, property setter doesn't gets called and although value is cleared in TextBox, 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"/>

Solution

  • 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"/>