AvaloniaUI / avalonia-dotnet-templates

Avalonia Templates for `dotnet new`
MIT License
507 stars 85 forks source link

BindingPlugins.DataValidators.RemoveAt(0) is too magical in the template #262

Open duongphuhiep opened 3 months ago

duongphuhiep commented 3 months ago

Is your feature request related to a problem? Please describe.

The value 0 is too "magic" IMO, if we upgrade the Avalonia version then the value 0 might not apply and might cause unwanted regression.

https://github.com/AvaloniaUI/avalonia-dotnet-templates/blob/7d00e7b665d9ccc80e8c7f621ec66204253d2e6d/templates/csharp/app-mvvm/App.axaml.cs#L27

// Line below is needed to remove Avalonia data validation.
// Without this line you will get duplicate validations from both Avalonia and CT
BindingPlugins.DataValidators.RemoveAt(0);

Describe the solution you'd like

Replace the 0 with something less magic which stand more chance for future Avalonia update.

// Line below is needed to remove Avalonia data validation.
// Without this line you will get duplicate validations from both Avalonia and CT
BindingPlugins.DataValidators.Remove(BindingPlugins.DataValidators.First(plugin => plugin is DataAnnotationsValidationPlugin));

Describe alternatives you've considered

Find a way in avalonia or CT to disable this validation by configuration, instead of adding it then removing it.

Additional context

No response

duongphuhiep commented 3 months ago

OR the template should simply follow the official documentation

private void DisableAvaloniaDataAnnotationValidation()
{
    // Get an array of plugins to remove
    var dataValidationPluginsToRemove =
        BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();

    // remove each entry found
    foreach (var plugin in dataValidationPluginsToRemove)
    {
        BindingPlugins.DataValidators.Remove(plugin);
    }
}

public override void OnFrameworkInitializationCompleted()
{
    // Avoid duplicate validations from both Avalonia and CT. More info: https://docs.avaloniaui.net/docs/guides/development-guides/data-validation#manage-validationplugins
    DisableAvaloniaDataAnnotationValidation();

    if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
    {
        desktop.MainWindow = new MainWindow
        {
            DataContext = new MainWindowViewModel(),
        };
    }

    base.OnFrameworkInitializationCompleted();
}
maxkatz6 commented 3 months ago

I think DataAnnotationsValidationPlugin was made internal at some point temporary, and then was reverted. Which is why templates are changed, but documentation wasn't.

PRs are welcomed to change it back in the templates.