我试图使一个WinForms用户控件与Collection<T>
作为一个属性(其中T代表一些自定义类)。我已经读了很多关于这个话题,但是我不能让它在设计时正常工作(在运行时一切都很好)。更准确地说:当我点击属性窗口中的"…"按钮时,集合编辑器显示良好,我可以添加和删除项目。但是,当我单击OK按钮时,什么也没有发生,当我重新打开收集编辑器时,所有项目都丢失了。当我查看设计器文件时,我看到我的属性被分配为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类:
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]; }
}
}
步骤类:
[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);
}
}
我已经尝试过的事情:
- 使Step类成为如下所述的组件:http://www.codeproject.com/Articles/5372/How-to-Edit-and-Persist-Collections-with-Collectio
- 将
Collection<Step>
更改为继承System.Collections.CollectionBase(也在前一篇代码项目文章中描述)的自定义集合类StepCollection
- 将DesignerSerializationVisibility设置为Content,如下所述:设计时用户控件中的集合编辑器当它被设置为Visible时,设计师将null赋给我的属性;当设置为Content时,设计器不分配任何内容。
- 我也发现了这一点:如何使一个集合的用户控制,可以在设计时编辑?但是CollectionBase类已经为我做了。 调试了很多,但是因为没有例外,我真的不知道出了什么问题。当我向collectionForm的关闭事件添加事件侦听器时,我可以看到(collectionForm的)EditValue属性仍然为空,即使我在集合编辑器中添加了几个步骤。但我也不知道为什么…
当完成这篇文章时,我刚刚发现了这个主题:在设计模式下编辑集合的最简单方法?这与我遇到的问题完全相同,但是我不能使用建议的答案,因为我没有使用标准集合。
在CodeProject上查看这篇伟大的文章,我测试了它们,它们都可以工作。
-
使用集合编辑器编辑多种类型的对象并序列化对象
-
如何编辑和保存收藏与CollectionEditor(你提到它不工作,但我检查了它,它工作)
我认为你没有应用的主要关键区别:
- 支持属性更改
- 为支持InstanceDescriptor的Collection Item类创建一个TypeConverter。
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;
}
注意方法中的第二行,它将一个新的Collection赋给初始值。通过这样做,我的集合是持久化的,并且一切都工作得很好。
我现在唯一想要修复的是对设计器文件的序列化。当前生成的代码如下:
// 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(因为组件总是在设计器文件中初始化)。
我知道这是一个完全不同于我的第一个问题,所以也许我会开始一个新的问题。但如果有人已经知道答案了,那就太好了!
更新:我找到了解决问题的办法。
从Component和CollectionBase继承是不可能的,因为c#不允许。实现将我的自定义集合转换为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