开发者

Clearing Textbox does not set binding to null

开发者 https://www.devze.com 2022-12-16 03:41 出处:网络
I am having difficulty setting an empty TextBox to null on an nullable DB Field. XAML <y:TextBox Text=\"{Binding Year1Cost, Mode=TwoWay,

I am having difficulty setting an empty TextBox to null on an nullable DB Field.

XAML

<y:TextBox Text="{Binding Year1Cost, Mode=TwoWay,  
     UpdateSourceTrigger=PropertyChanged,   
     NotifyOnValidationError=True,   
     ValidatesOnDataErrors=True,   
     ValidatesOnExceptions=True,  
     StringFormat=\{0:c\}}" Grid.Row="3" Grid.Column="1" />

When I enter any value into it the binding is fine and the entered value is passed

When I leave a null value alone a null is passed

If I delete the value from the TextBox the value passed is the Original value of the Textbox and the UI is not notified of the ch开发者_StackOverflow中文版ange Grrrrrrrrrrrrrrrr

I have spent a long time checking out options nothing short of putting code behind the OnTextChanged of every nullable field I cannot see the efficiency in doing this.

Thanks in advance:

ps. Have looked at TargetNullValue to no success

Visual Studio 2008 - SP1 - .Net 3.5


Set the property TargetNullValue of the binding to String.Empty:

<TextBox Text="{Binding TargetNullValue={x:Static sys:String.Empty}}"/>

I tried it and it works for me.

And if I am not wrong (please forgive me if I am), you should set the property StringFormat like this:

StringFormat={}{0:C}

This is even probably the reason of the exception you got.


Consider using a value converter. You should be able to implement the ConvertBack method to translate empty strings into nulls.


For me only converter works : Here's a link

public class NullableConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
       return value == null ? string.Empty : String.Format(culture, "{0}", value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
       return string.IsNullOrEmpty(String.Format(culture, "{0}", value)) ? null : value;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消