dotnet / maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
https://dot.net/maui
MIT License
22.26k stars 1.76k forks source link

BindableProperty validation does not throw an ArgumentException, although it is documented as such #25823

Open MSwit opened 1 week ago

MSwit commented 1 week ago

Description

When a validation callback of a BindableProperty returns false, no Exeption is raised as documented here

Example:

public class CustomControl : ContentView
    {
        public static readonly BindableProperty CustomTextProperty = BindableProperty.Create(
            nameof(CustomText),
            typeof(string),
            typeof(CustomControl),
            defaultValue: string.Empty,
            validateValue: (bindable, value) =>
            {
                // This validator returns false for empty strings
                // We expect this to throw an ArgumentException, but it doesn't
                return !string.IsNullOrEmpty((string)value);
            }
        );

        public string CustomText
        {
            get => (string)GetValue(CustomTextProperty);
            set => SetValue(CustomTextProperty, value);
        }

        public CustomControl()
        {
            // Basic layout for demonstration
            Content = new Label
            {
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions = LayoutOptions.Center,
            };
            CustomText = "some valid text";

            // Set up the binding correctly
            ((Label)Content).SetBinding(Label.TextProperty, new Binding(nameof(CustomText), source: this));
        }
    }

Steps to Reproduce

Link to the reproduction link below

Link to public reproduction project repository

https://github.com/zauberzeug/Maui_BindableProperty_validation

Version with bug

8.0.40 SR5

Is this a regression from previous behavior?

Not sure, did not test other versions, Yes, this used to work in Xamarin.Forms

Last version that worked well

Unknown/Other

Affected platforms

iOS, Android, I was not able test on other platforms

Affected platform versions

iOS 17, Android 13

Did you find any workaround?

Throw an Exeption inside the validation callback.

   public static readonly BindableProperty CustomTextProperty = BindableProperty.Create(
            nameof(CustomText),
            typeof(string),
            typeof(CustomControl),
            defaultValue: string.Empty,
            validateValue: (bindable, value) =>
            {
                if (string.IsNullOrEmpty((string)value))
                    throw new ArgumentException();
                return true;
            }
        );
ninachen03 commented 1 week ago

This issue has been verified using Visual Studio 17.13.0 Preview 1.0 (8.0.93 & 8.0.3). Can repro on iOS/Android platform.