在XAML \Windows 8商店应用程序中将数据绑定为可空类型 [英] Databind a nullable type in XAML\Windows 8 store app
问题描述
我在XAML一个TextBox其中我想数据绑定到一个可空int类型。这是我的文本框代码和链接器:
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?
我使用XAML和放大器; C#设计一个Windows应用商店的应用程序。
I'm using XAML & C# to design a windows store application.
在此先感谢。
推荐答案
我同意萨沙的答案,但如果你需要一个NullableValueConverter的改善将是
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;
}
}
请注意,这是使用WPF这样的方法签名测试可以是从WinRT的不同
Note that this was tested using WPF so the method signatures may be different from WinRT.
这篇关于在XAML \Windows 8商店应用程序中将数据绑定为可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!