gpt4 book ai didi

C# 启用/禁用 PropertyGrid 中的字段

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:03 24 4
gpt4 key购买 nike

我正在开发一个用户控件库,我需要在其中为程序员提供一个属性网格来自定义我的控件的属性。
如果程序员使用 System.Windows.Forms.PropertyGrid(或 Visual Studio 的设计器)
System.Windows.Forms.PropertyGrid 中的某些属性字段应该根据同一用户控件的某些其他属性启用/禁用。
怎么做?

示例场景

这不是实际的例子,只是一个例子。
例如:UserControl1 有两个自定义属性:
MyProp_Caption:字符串

MyProp_Caption_Visible:一个 bool 值
现在,仅当 MyProp_Caption_Visible 为真时,才应在 PropertyGrid 中启用 MyProp_Caption

UserControl1 的示例代码

public class UserControl1: UserControl <br/>
{
public UserControl1()
{
// skipping details
// label1 is a System.Windows.Forms.Label
InitializeComponent();
}
[Category("My Prop"),
Browsable(true),
Description("Get/Set Caption."),
DefaultValue(typeof(string), "[Set Caption here]"),
RefreshProperties(RefreshProperties.All),
ReadOnly(false)]
public string MyProp_Caption
{
get
{
return label1.Text;
}
set
{
label1.Text = value;

}
}
[Category("My Prop"),
Browsable(true),
Description("Show/Hide Caption."),
DefaultValue(true)]
public bool MyProp_Caption_Visible
{
get
{
return label1.Visible;
}
set
{
label1.Visible = value;
// added as solution:
// do additional stuff to enable/disable
// MyProp_Caption prop in the PropertyGrid depending on this value
PropertyDescriptor propDescr = TypeDescriptor.GetProperties(this.GetType())["MyProp_Caption"];
ReadOnlyAttribute attr = propDescr.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
if (attr != null)
{
System.Reflection.FieldInfo aField = attr.GetType().GetField("isReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
aField.SetValue(attr, !label1.Visible);
}
}
}
}

此 UserControl1 上的 PropertyGrid 示例代码

  • tstFrm 是一个简单的 Form,具有以下两个数据成员

        private System.Windows.Forms.PropertyGrid propertyGrid1;
    private UserControl1 userControl11;

并且我们可以通过propertyGrid1自定义userControl1如下:

public partial class tstFrm : Form
{
public tstFrm()
{
// tstFrm embeds a PropertyGrid propertyGrid1
InitializeComponent();
propertyGrid1.SelectedObject = userControl11;
}
}

如何根据 MyProp_Caption_Visible 的值启用/禁用属性网格中的字段 MyProp_Caption?

最佳答案

(由 OP 在问题编辑中回答。转换为社区维基答案。参见 Question with no answers, but issue solved in the comments (or extended in chat))

OP 写道:

Solved!

thanks to @Simon Mourier! Posting the edited code. Result:

ENABLEDDISABLED

关于C# 启用/禁用 PropertyGrid 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18985236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com