我有两个从属属性-已婚和配偶的名字。如果已婚为假,则配偶姓名应为只读。我在搜索时遇到了此解决方案,但在Xceed PropertyGrid上不起作用-输入空引用错误
此方法适用于WinForms,但不适用于Wpf。
public class Employee
{
string name;
bool isMarried;
string spouseName;
public string Name
{
get { return name; }
set { name = value; }
}
[System.ComponentModel.RefreshProperties(RefreshProperties.All)]
public bool IsMarried
{
get { return isMarried; }
set
{
isMarried = value;
bool newValue = !value;
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(this.GetType())["SpouseName"];
ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
isReadOnly.SetValue(attrib, newValue);
}
}
[ReadOnly(true)]
public string SpouseName
{
get { return spouseName; }
set
{
spouseName = value;
}
}
}
Fieldinfo isReadOnly返回null