绑定到TextBox.Text的DataContext属性在清除TextBox时不会更新

时间:2014-10-28 09:26:05

标签: c# silverlight

在我的SilverLight申请中,我TextBox.Text绑定了nullable decimal DataContext。当我将TextBox的值(例如从25更改为6)工作时,DataContext上的属性的setter被执行并且后备字段已更新,但是当我手动清除TextBox时它不起作用,不会调用setter。

[DataMember]
public decimal? Order 
{
    get { return order; }
    set { order = value; }
}
decimal? order;

xaml片段:

<Input:PraTextBox
    Text="{Binding Path=Order, Mode=TwoWay}"
    IsEnabled="{Binding Path=IsDefaultVisibleEnabled, Mode=TwoWay}"/>

2 个答案:

答案 0 :(得分:2)

普通TextBox默认情况下仅更新LostFocus上的绑定源。我不知道你PraTextBox做了什么。但我建议您检查是否更新了LostFocusPropertyChanged上的来源。

尝试在绑定中指定UpdateSourceTrigger

Text="{Binding Path=Order, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

接下来尝试:使用转换器:

public class NullableDecimalConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
        CultureInfo culture) { return value; }

    public object ConvertBack(object value, Type targetType, object parameter,
        CultureInfo culture)
    {
        string decimalString = value as string;
        decimal parsedDecimal;
        if (decimalString != null && Decimal.TryParse( decimalString,
                                                       out parsedDecimal ))
            return parsedDecimal;
        else
            return null;
    }
}

绑定:

Text="{Binding Path=Order, Mode=TwoWay,
    Converter={StaticResource myNullableDecimalConverter}}"

答案 1 :(得分:0)

显然Silverlight(和WPF一样,只要我知道)将空TextBox视为空字符串而不是null ..而且他们认为空字符串转换为数字是不确定的,所以如果将数字绑定到文本框,一旦将值设置为数字,就不能清除它了。

PropetyChanged并不是因为数字没有改变而引发的 - 获取调试器并自己查看。

在Silverlight 5中,您可以使用:

overflow: scroll

其中SOMEFIELD是Nullable或其他数字..