请看下面一行
<TextBox Text="{Binding Price}"/>
上面的 Price 属性是一个 Decimal?(可为空的小数)。
Decimal?
I want that if user deletes the content of the textbox (i.e. enters empty string, it should automatcally update source with null (Nothing in VB).
有什么办法可以让我做“ Xamly”吗?
可以尝试使用 ValueConverter (IValueConverter) Http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
在我的后脑勺这里,大概是这样的:
public class DoubleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return (double)value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var doubleValue = Convert.ToDouble(value); return (doubleValue == 0 ? null : doubleValue); } }
(Might need some tweaking though)
这个值转换器应该可以做到这一点:
public class StringToNullableDecimalConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { decimal? d = (decimal?)value; if (d.HasValue) return d.Value.ToString(culture); else return String.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string s = (string)value; if (String.IsNullOrEmpty(s)) return null; else return (decimal?)decimal.Parse(s, culture); } }
在资源中声明此转换器的一个实例:
<Window.Resources> <local:StringToNullableDecimalConverter x:Key="nullDecimalConv"/> </Window.Resources>
在你的装订中使用它:
<TextBox Text="{Binding Price, Converter={StaticResource nullDecimalConv}}"/>
请注意,TargetNullValue在这里是不合适的: 它用于定义当绑定的 source为空时应该使用哪个值。这里 Price不是源,它是源的属性..。
TargetNullValue
source
Price
我使用的是.NET 3.5 SP1,所以它非常简单:
<TextBox Text="{Binding Price, TargetNullValue=''}"/>
它的意思是(感谢 Gregor 的评论) :
<TextBox Text="{Binding Price, TargetNullValue={x:Static sys:String.Empty}}"/>
sys是导入的 mscorlib中 System的 xml 命名空间:
sys
mscorlib
System
xmlns:sys="clr-namespace:System;assembly=mscorlib"
希望这有帮助。