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"/>
Answer: 1
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)
by : Simon P Stevenshttp://stackoverflow.com/users/119738Answer: 2
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; }
by : ChrisBDhttp://stackoverflow.com/users/102238Answer: 3
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"/>
by : WPF Userhttp://stackoverflow.com/users/355820Answer: 4
Akjoshi, I have a working solution! You need to change your integer property to Naullable (i.e. int? ), see the following snippet:
private int? _maxOccurrences; public int? MaxOccurrences { get { return _maxOccurrences; } set { _maxOccurrences = value; } }
You also need to add a value converter to convert the empty string to null value, see the following code snippet:
public class EmptyStringToNullConverter : 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()) ? null : value; }
No comments:
Post a Comment
Send us your comment related to the topic mentioned on the blog