开发者

Custom control generate code at design time

Is it possible to write a control which can create/ modify a code file in the same project - (Along the lines of the how the form designer works). I can't see the actual creating / modification of files being troubles开发者_如何学运维ome - however I would like to avoid the 'xyz file has been modified - would you like to reload it?' dialogue.

To be honest I'm not expecting that I can without writing a plug in or something of the like.


Absolutley, take a look at the CodeDom: -

http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx

Alternatively look into creating a Visual Studio Add-in: -

http://www.c-sharpcorner.com/UploadFile/mgold/AddIns11292005015631AM/AddIns.aspx

Cheers,

Phil.


This is indeed possible to do. After referencing EnvDTE

using EnvDTE;


    var host = this.Container as IDesignerHost;
    var dte = host.GetService(typeof(DTE)) as DTE;
    var activeDoc = dte.ActiveDocument;
    var project = activeDoc.ProjectItem.Collection.Parent as Project;
    project.ProjectItems.AddFromFile("\\Test.cs");


As Plip stated, use CodeDom and more specifically - CodeDocSerialier. Here`s a short example:

[Serializer(typeof(MySerializer))]
class MyControl : Control {}

class MySerializer : CodeDomSerializer
{
    public override object Serialize(IDesignerSerializationManager manager, object value)
    {
      CodeDomSerializer baseSerializer;
      CodeStatementCollection statements;
      CodeExpression targetObject;

      if(manager == null || value == null)
      {
        return null;
      }

      baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(MyControl).BaseType, typeof(CodeDomSerializer));
      statements = baseSerializer.Serialize(manager, value) as CodeStatementCollection;
      if(statements == null)
      {
        statements = new CodeStatementCollection();
      }

      targetObject = GetExpression(manager, value);
      if(targetObject != null)
      {
        // add 'myControl.Visible = true;' statement.
        statements.Add(
          new CodeAssignStatement(
            new CodeFieldReferenceExpression(targetObject, "Visible"),
            new CodePrimitiveExpression(true)));
      }
      return statements;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜