I have taken the code inside the set
from codeproject. I'm trying to make the property Phone
readonly, if the QRType
is not equal to Contact
or Phone
(QRType is an enum):
public QRType Type
{
get { return type; }
set
{
type = value;
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(GetType())["Phone"];
ReadOnlyAttribute attribute = (ReadOnlyAttribute)
descriptor.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly",
BindingFlags.NonPublic |
BindingFlags.Instance);
bool v = (type != QRType.Contact && type != QRType.Phone);
fieldToChange.SetValue(attribute, v );
}
}
The above code does not work correctly and the Phone field is always grayed out, while setting the values like:
fieldToChange.SetValue(attribute, true );
fieldToChange.SetValue(attribute, false );
both works correctly. What is wrong with it?
UPdate:
It is funny that without using &&
it works:
fieldToChange.SetValue(attribute, type != QRType.Contact);