CommunityToolkit / MVVM-Samples

Sample repo for MVVM package
Other
1.11k stars 222 forks source link

How to work with nullable properties? #118

Open ComptonAlvaro opened 1 year ago

ComptonAlvaro commented 1 year ago

I have a Textbox that binds to a long? property in the view model.

I would like that if the TextBox is empty, to set the value of the property to null. But when the TextBox is empty, the property in the view model is not changed, it keeps the last digit that the TextBox had.

I would like to have null when the TextBox is empty.

I was trying to intercept the prperty changed event in this way:

    [ObservableProperty]
    long? _myProperty;

    partial void OnMyPropertyChanging(long? value)
    {
        Console.WriteLine($"Name has changed to {value}");
        _myproperty = value;
    }

However the behaviour is not very good. When I write this secuence in the TextBox I get this behaviour:

1.- Write 5. I get 5 as value. 2.- Delete 5, the method is not execute 3.- Write 5, the method is not execute 4.- Write 5, the value of the method is 55

How could I bind to a long? property?

Thanks.

ellovich commented 7 months ago

Same problem...

DaveInCaz commented 7 months ago

Maybe this is what you are looking for: https://stackoverflow.com/a/3302580/3195477

Summary:

Set TargetNullValue to string.empty on the Binding and it will convert the empty string to null,