Reputation: 416
In my universal app if I enter a value in a textbox the entered value is not transferred into the backing object. that happens only to nullable values, as soon as i make the variable not nullable it is working as expected.
What I found strange is, if i set TargetNullValue='' to my binding and clear the textbox, then the backing object is called and the value is set to null as expected, but if i then enter a new value into the textbox that value will not be transferred into the backing object.
My problem is quite similar to this one, I think: UWP - Bind TextBox.Text to Nullable<int>
Only difference is, that I do not get any error message, it just doesn't happen anything. I even tried the converter-workaround. the converter is called but the value that is returned by the converter will not get set into the object.
I found a lot of post like the one I linked above, but in all cases there were some kind of error messages returned. again, in my case it just happens nothing, as if there is no binding.
This is my code:
<Grid.Resources>
<utils:NullableValueConverter x:Key="NullableIntConverter" />
</Grid.Resources>
<TextBox Text="{Binding Level, Mode=TwoWay, Converter={StaticResource NullableIntConverter}, TargetNullValue=''}" PlaceholderText="Level"/>
The backing object:
public class Unit
{
public int? Level { get; set; }
}
The converter:
public class NullableValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return string.IsNullOrEmpty(value.ToString()) ? null : value;
}
}
Upvotes: 1
Views: 968
Reputation: 1385
Please try to return an int value in ConvertBack() as below.
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
int data;
if (string.IsNullOrEmpty((string)value) || !int.TryParse((string)value, out data))
{
return null;
}
else
{
return data;
}
}
Upvotes: 4