简体   繁体   中英

C# UserControl Custom Properties

i am creating a usercontrol which provides all of the common validations for a range of textbox styles: alpha, number, decimal, SSN, etc. so, when a developer using this control selects the alpha style, they can also select another property which defines a string of special characters that could also be allowed during validation.

but when the decimal style, for instance, is selected, i'd like to simply disable the special characters property so it is not settable when a style is selected that doesn't allow special characters.

how can i achieve this goal?

thanks

You can't disable properties in C# - they're part of your type's interface, which promises that callers can bind to those operations at compile-time.

The simplest implementation is to ignore the special characters when the user specifies an incompatible style. This is idiomatic .NET behavior - for example, see the CompareValidator , which has some mutually exclusive properties:

Do not set both the ControlToCompare and the ValueToCompare property at the same time. You can either compare the value of an input control to another input control, or to a constant value. If both properties are set, the ControlToCompare property takes precedence.

Having said that, this technique makes classes harder to use than they need to be - their interfaces don't really tell you how to use them. I recommend breaking your validator into two classes: one for alphabetic validations and one for numeric validations.

Alternately, you can throw an exception in your setter when the style doesn't support special characters. Often, that's too drastic, but it makes it clear to the client programmer that they've done something invalid.

I would consider doing it in the setter of the properties

private string specialCharacters = "";
public string SpecialCharacters
{
   get { if ( usingDecimals ) 
           specialCharacters = "";

        return specialCharacters; }

   set { if( usingDecimals )
            value = "";

         specialCharacters = value; }
}

private boolean usingDecimals = false;
public boolean UsingDecimals
{  get { return usingDecimals; } 
   set { usingDecimals = value;
         if( usingDecimals )
             specialCharacters = ""; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM