C# Property Grid属性选择多次显示表单

标签 c# winforms propertygrid

我创建了一个具有自定义数组值的属性网格。当用户选择其中一个下拉列表时,我希望它显示一个表单。我的问题不是它不起作用,不是它过于活跃,尽管只声明了一次,但它显示了大约 6 次表单。如果我选择 ShowDialog,它会显示两次表单,并在尝试关闭第二个对话框时创建另外两个表单实例。下面是我正在使用的代码。我不知道哪里出了问题。

//Property Grid Type
 internal class TransferConnectionPropertyConverter : StringConverter
    {
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return true;
        }

        public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            return new StandardValuesCollection(new string[] { "", NEW_CONN });
        }            
    }

//Property Grid Node
[Category("Connection"),
Description("Specifies the type of connection for this task.")]
[TypeConverter(typeof(TransferConnectionPropertyConverter))]
public string TransferProtocol
{
    get
    {
         if (stConnectionType == NEW_CONN)
         {
              ConnectionDetailsForm connDetails = new ConnectionDetailsForm();
              connDetails.Show();                        
         }
         return stConnectionType;
    }
    set
    {
         stConnectionType = value;
    }                                       
}

最佳答案

为此您需要一个编辑器,并且您肯定不希望在属性的 get property 期间显示表单,因为在 PropertyGrid 的生命周期中可能会多次调用它.

简单类(来自 this example ):

public class StringEditor : UITypeEditor {
  public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
    return UITypeEditorEditStyle.Modal;
  }

  public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
    IWindowsFormsEditorService svc = (IWindowsFormsEditorService)
      provider.GetService(typeof(IWindowsFormsEditorService));
    if (svc != null) {
      svc.ShowDialog(new ConnectionDetailsForm());
      // update etc
    }
    return value;
  }
}

然后你为这个编辑器装饰你的属性(注意,我删除了转换器,因为你的属性只是一个字符串,没有什么可转换的):

[Category("Connection")]
[Description("Specifies the type of connection for this task.")]
[Editor(typeof(StringEditor), typeof(UITypeEditor))]
public string TransferProtocol {
  get {
    return stConnectionType;
  }
  set {
    stConnectionType = value;
  }
}

关于C# Property Grid属性选择多次显示表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11394196/

相关文章:

c# - 初始化优先级——const vs readonly vs static readonly

c# - 如何使控制台能够打印 65535 个 UNICODE 字符中的任何一个

c# - .net core - 模型虚拟属性未加载

C# - 终止 Application.Run()

c# - 显示枚举中的 int 值

c++ - QtPropertyBrowser 和值更改信号

c# - If 条件简化

C# 应用程序不关闭

c# - 使可为空的数字向上向下c#

c# - PropertyGrid 集合显示文本