设计时集合编辑器数据丢失。

3
我正在尝试制作一个WinForms用户控件,其中包含一个Collection<T>属性(其中T代表一些自定义类)。我已经阅读了很多关于这个主题的内容,但是我无法在设计时正常工作(运行时一切正常)。更精确地说:当我点击属性窗口中的“…”按钮时,集合编辑器显示得很好,我可以添加和删除项目。但是当我单击“确定”按钮时,什么也不会发生,并且当我重新打开集合编辑器时,所有项目都丢失了。当我查看设计器文件时,我发现我的属性被分配为null,而不是组合的集合。下面是最重要的代码:

用户控件:
[Browsable(true),
 Description("The different steps displayed in the control."),
 DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
 Editor(typeof(CustomCollectionEditor), typeof(UITypeEditor))]
public StepCollection Steps
{
    get
    {
        return wizardSteps;
    }
    set
    {
        wizardSteps = value;
        UpdateView(true);
    }
}

StepCollection class:

public class StepCollection : System.Collections.CollectionBase
{
    public StepCollection() : base() { }
    public void Add(Step item) { List.Add(item); }
    public void Remove(int index) { List.RemoveAt(index); }
    public Step this[int index]
    {
        get { return (Step)List[index]; }
    }
}

Step class:

[ToolboxItem(false),
DesignTimeVisible(false),
Serializable()]
public class Step : Component
{
    public Step(string name) : this(name, null, StepLayout.DEFAULT_LAYOUT){ }
    public Step(string name, Collection<Step> subSteps) : this(name, subSteps, StepLayout.DEFAULT_LAYOUT){ }
    public Step(string name, Collection<Step> subSteps, StepLayout stepLayout)
    {
        this.Name = name;
        this.SubSteps = subSteps;
        this.Layout = stepLayout;
    }
    // In order to provide design-time support, a default constructor without parameters is required:
    public static int NEW_ITEM_ID = 1;
    public Step()
        : this("Step" + NEW_ITEM_ID, null, StepLayout.DEFAULT_LAYOUT)
    {
        NEW_ITEM_ID++;
    }
    // Some more properties
}

CustomCollectionEditor:

class CustomCollectionEditor : CollectionEditor
{
    private ITypeDescriptorContext mContext;

    public CustomCollectionEditor(Type type) : base(type) { }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        mContext = context;
        return base.EditValue(context, provider, value);
    }
    protected override object CreateInstance(Type itemType)
    {
        if (itemType == typeof(Step))
        {
            Step s = (Step)base.CreateInstance(itemType);
            s.parentContext = mContext; // Each step needs a reference to its parentContext at design time
            return s;
        }
        return base.CreateInstance(itemType);
    }
}

我已经尝试过以下方法:
1. 将Step类作为组件,如此处所述:http://www.codeproject.com/Articles/5372/How-to-Edit-and-Persist-Collections-with-Collectio 2. 将Collection<Step>更改为自定义集合类StepCollection,继承自System.Collections.CollectionBase(也在前面的代码项目文章中描述)。
3. 将DesignerSerializationVisibility设置为Content,如此处所述:Collection Editor within a User Control at Design Time。当它设置为Visible时,设计师将null分配给我的属性;当它设置为Content时,设计师不会分配任何东西。
4. 我还发现了这个:How to make a UserControl with a Collection that can be edited at design time?,但是CollectionBase类已经为我完成了这项工作。
5. 进行了大量调试,但由于没有异常,我真的不知道出了什么问题。当我向collectionForm的关闭事件添加事件侦听器时,即使我在集合编辑器中添加了一些步骤,我也可以看到collectionForm的EditValue属性仍然为null。但我也不知道这是为什么...
在完成这篇文章时,我刚发现了这个主题:Simplest way to edit a collection in DesignMode?。这正是我遇到的相同问题,但是我不能使用所提出的答案,因为我没有使用标准集合。
2个回答

1

谢谢你的回答。我会看一下并尝试着去做。 - user1176420

0

Reza Aghaei提到的文章非常有趣。不过我认为我已经接近一个更简单的解决方案来解决我的问题:

正如我已经注意到的,尽管向集合添加了项目,但collectionForm的EditValue属性仍保持为空。现在,我实际上不确定集合编辑器的EditValue方法内部发生了什么,但我猜测它捕获了一个异常,因为我的集合的初始值为null(它没有在构造函数中初始化),因此返回null而不是创建一个新的集合。通过对自定义集合编辑器类进行以下更改,我得到了非常有希望的结果:

public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
    mContext = context;
    if (value == null) value = new Collection<Step>();
    Collection<Step> result = (Collection<Step>)base.EditValue(context, provider, value);
    if (result != null && result.Count == 0) return null;
    return result;
}

请注意方法内的第二行,它将一个新的集合分配给初始值。通过这样做,我的集合被持久化,一切都几乎正常工作。
我现在想要解决的唯一问题是序列化到设计文件中。目前会产生类似以下内容的东西:
// wizardStepsControl1
// ...
this.wizardStepsControl1.Steps.Add(this.step1);
// ...

// step1
// Initialization of step1

这段代码会抛出异常,因为 wizardStepsControl1.Steps 从未初始化。我希望的结果是这样的:
this.wizardStepsControl1.Steps = new Collection<Step>();
this.wizardStepsControl1.Steps.Add(step1);
// ...

更好的方法是在一开始初始化整个集合,然后将其分配给我的控件的Steps属性。 我会尽力让它工作,并在这里发布一些更新。也许需要实现InstanceDescriptor或使我的自定义Collection类继承自Component(因为组件始终在设计器文件中初始化)。
我知道这与我的第一个问题完全不同,所以也许我会为此开始一个新问题。但是,如果有人已经知道答案,那么在这里听到它会很棒!
更新: 我找到了解决我的问题的方法。
由于C#不允许从Component和CollectionBase继承,因此这是不可能的。 将我的自定义集合转换为InstanceDescriptor的TypeConverter也不起作用(我不知道为什么,我想这是因为Collection以不同于普通自定义类的方式序列化)。
但是通过创建CodeDomSerializer,我能够向生成的设计器代码添加代码。 这样,如果在设计时间添加了某些项目,我就可以初始化我的集合:
public class WizardStepsSerializer : CodeDomSerializer
{
    /// <summary>
    /// We customize the output from the default serializer here, adding
    /// a comment and an extra line of code.
    /// </summary>
    public override object Serialize(IDesignerSerializationManager manager, object value)
    {
        // first, locate and invoke the default serializer for 
        // the ButtonArray's  base class (UserControl)
        //
        CodeDomSerializer baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(WizardStepsControl).BaseType, typeof(CodeDomSerializer));

        object codeObject = baseSerializer.Serialize(manager, value);

        // now add some custom code
        //
        if (codeObject is CodeStatementCollection)
        {

            // add a custom comment to the code.
            //
            CodeStatementCollection statements = (CodeStatementCollection)codeObject;
            statements.Insert(4, new CodeCommentStatement("This is a custom comment added by a custom serializer on " + DateTime.Now.ToLongDateString()));

            // call a custom method.
            //
            CodeExpression targetObject = base.SerializeToExpression(manager, value);
            WizardStepsControl wsc = (WizardStepsControl)value;
            if (targetObject != null && wsc.Steps != null)
            {
                CodePropertyReferenceExpression leftNode = new CodePropertyReferenceExpression(targetObject, "Steps");
                CodeObjectCreateExpression rightNode = new CodeObjectCreateExpression(typeof(Collection<Step>));
                CodeAssignStatement initializeStepsStatement = new CodeAssignStatement(leftNode, rightNode);
                statements.Insert(5, initializeStepsStatement);
            }

        }

        // finally, return the statements that have been created
        return codeObject;
    }
}

通过使用DesignerSerializerAttribute将此序列化程序与我的自定义控件相关联,设计文件中会生成以下代码:
// 
// wizardStepsControl1
// 
// This is a custom comment added by a custom serializer on vrijdag 4 september 2015
this.wizardStepsControl1.Steps = new System.Collections.ObjectModel.Collection<WizardUserControl.Step>();
// ...
this.wizardStepsControl1.Steps.Add(step1);
// ...

这正是我想要的。

我大部分的代码都是从https://msdn.microsoft.com/en-us/library/system.componentmodel.design.serialization.codedomserializer(v=vs.110).aspx中获取的。


你好,我遇到了同样的问题,尽管你提供了答案,但我仍然无法解决,能否请您提供一个解决方案? - Asım Gündüz
你指的是哪个问题?不幸的是我已经不再从事C#开发,所以我不知道我是否能再帮助你了。 - user1176420

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接