如何基于从另一个属性中选择的值设置ReadOnly属性?

时间:2019-11-08 04:03:56

标签: xceed

我有两个从属属性-已婚和配偶的名字。如果已婚为假,则配偶姓名应为只读。我在搜索时遇到了此解决方案,但在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

0 个答案:

没有答案