Home > Net >  Workaround for accessing non-static property in a static context for Validation C#
Workaround for accessing non-static property in a static context for Validation C#

Time:02-08

Let's say I have the class Wallet:

public class Wallet
{
       public double Min { get; set; }

       public double Max { get; set; }

       public double Value { get; set; }
}

And let's say that the data is read from a database.

The user is able to modify Value from the UI.

I want to validate it somehow, so my initial thought was:

[Range(Min, Max, ErrorMessage = "The value is outside of bounds.")]
public double Value { get; set; }

But an error is thrown: Cannot access non-static property in a static context attribute.

Is there a workaround or do I have to create a custom validation?

Context: WPF MVVM application, C#

CodePudding user response:

You could move that validation to the setter, and throw the exact validation exception that the attribute class throws if any validation erros occur.

  •  Tags:  
  • Related