Tutorial :WPF binding not working properly with properties of int type



Question:

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:1

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


Solution:2

If you don't want to use a Nullable integer, you can use a converter that converts the empty string to 0, see the code below:

public class EmptyStringToZeroConverter : IValueConverter  {      #region IValueConverter Members        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)      {          return value;      }        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)      {          return value == null || string.IsNullOrEmpty(value.ToString())              ? 0              : value;      }        





        
Previous
Next Post »