问题
I have a TextBox in XAML which I'm trying to databind to a nullable int. This is the code for my textbox and linked converter:
<TextBox x:Name="textArea" InputScope="Number" Text="{Binding Area, Mode=TwoWay, Converter={StaticResource NullableValueConverter}}" />
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)
{
if (String.IsNullOrEmpty(value.ToString()))
{
return null;
}
return value;
}
}
When every I enter a number in this textbox the databind doesn't seem to work and the datasource is always left as null. How can I get round this?
I'm using XAML & C# to design a windows store application.
Thanks in advance.
回答1:
I agree with Sacha's answer, but if you need a NullableValueConverter an improvement would be
public class NullableValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
return value == null ? string.Empty : value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
string s = value as string;
int result;
if (!string.IsNullOrWhiteSpace(s) && int.TryParse(s, out result))
{
return result;
}
return null;
}
}
Note that this was tested using WPF so the method signatures may be different from WinRT.
回答2:
In your binding handle TargetNullValue. Somewhat like:
You'll need to add mscorlib:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
and update your binding like so:
Source="{Binding Area,
TargetNullValue={x:Static sys:String.Empty},
Converter={StaticResource NullableValueConverter}}"
Actually you wont need the NullableValueConverter if you check for a null value in your XAML. This depends of course what else your converter is possibly supposed to handle.
Alternatively you could implement IDataErrorInfo. That is a bit more complex tho.
回答3:
There's no TargetNullValue
property on Binding class for Windows Store apps.
Phil's approach is valid and it works fine, just make sure you're using the correct method signatures as he suggested (and as you already did in your own version of NullableValueConverter
):
public class NullableValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return value == null ? string.Empty : value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
string s = value as string;
int result;
if (!string.IsNullOrWhiteSpace(s) && int.TryParse(s, out result))
{
return result;
}
return null;
}
}
来源:https://stackoverflow.com/questions/15406336/databind-a-nullable-type-in-xaml-windows-8-store-app