如何为字符串属性创建Modal UITypeEditor?

时间:2014-08-10 16:12:38

标签: c# propertygrid

我有一个属性,存储为字符串,并通过PropertyGrid进行编辑。它保存为一组逗号分隔值,例如ABC,DEF,GHI。我的用户可以直接编辑字符串,但值来自一组封闭的值。因此,他们从列表中选择更容易,更安全。

我根据优秀的答案here

编写了一个简单的自定义UITypeEditor

我还审核了this,但我并不理解它可能与我的问题有关。 8 - (

我设置了一个简单的表单,允许用户从列表中选择,并将拾取的值添加到要返回的值中。我的问题是没有返回值。我想知道这是否与字符串的不变性有关。然而,我正在做的事情可能是简单而愚蠢的事情。

以下是基于Marc答案的类型编辑器的代码:

   public class AirlineCodesEditor : UITypeEditor
    {

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value)
        {
            var svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            var codes = value as string;

            if (svc != null && codes != null)
            {
                using (var form = new AirlineCodesEditorGUI())
                {
                    form.Value = codes;
                    if (svc.ShowDialog(form) == DialogResult.OK)
                    {
                        codes = form.Value; // update object
                    }
                }
            }

            return value; // can also replace the wrapper object here
        }

    }

表格对于我的测试来说是微不足道的我只是用一些新值编辑了文本框:

   public partial class AirlineCodesEditorGUI : Form
    {


        public AirlineCodesEditorGUI()
        {
            InitializeComponent();

        }


        public string Value {
            get
            {
                return airlineCodes.Text;
            }

            set
            {
                airlineCodes.Text = value;
            } 
        }

        private void OnCloseButtonClick(object sender, System.EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }
    }  

也许有人会让我摆脱痛苦。

1 个答案:

答案 0 :(得分:0)

您只需要从表单中返回值,如下所示:

 if (svc.ShowDialog(form) == DialogResult.OK)
 {
     value = form.Value;
 }
相关问题