CommunityToolkit / CommunityToolkit/dotnet
Add some kind of [TrySetProperty] attribute
- Dominant language
- C#
- Stars
- 3.8k
- Forks
- 400
- PR merge metrics
- No merged PRs in 30d
Description
### Overview
The problem I would like to solve is:
Don't change a value when it fails validation but instead invoke the ErrorsChanged event, all of this just with attributes / code generators.
More in detail:
As soon as you don't want invalid values to be saved you can no longer work with simple attributes but have to use TrySetProperty. But TrySetProperty is missing an overload to invoke the ErrorsChanged event but only relies on the out parameter to deliver validation errors. Therefore any event based validation handling stops working and needs some kind of workaround (like firing additional OnPropertyChanged calls to process the validation errors or to manually call ValidateProperty again just so that the ErrorsChanged event gets invoked.
### API breakdown
```csharp
namespace CommunityToolkit.Mvvm.ComponentModel;
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public sealed class TrySetProperty : Attribute
{
}
```
### Usage example
```csharp
[ObervableObject]
[TrySetProperty]
[MaxLength(20)]
private string name;
```
which would generate something like
```csharp
private string name;
[MaxLength(20)]
public string Name
{
get => name;
set => TrySetProperty(ref name, value); // <- using a new overload that works with ErrorsChanged the same way as SetProperty(ref name, value, true) does.
```
### Breaking change?
I'm not sure
### Alternatives
Currently I only see one workaround if event based validation handling is used, doing an additional, unneeded validation just to trigger the event:
```csharp
private string name;
[MaxLength(20)]
public string Name
{
get => name;
set
{
if (!TrySetProperty(ref name, value, out _)) ValidateProperty(nameof(Name));
}
```
Every other workaround ignores events and just processes the provided `IReadOnlyCollection` out variable.
### Additional context
_No response_
### Help us help you
No, just wanted to propose this
Contributor guide
Assessment
This issue has not been assessed yet.