How to load a winform into winfrom container ?

Oct 11, 2010 at 10:46 AM

Hi guys, I have dicided to play a little bit with MEF2 and net3.5 and I have thougth it would be easy but I am stuck now. Generaly the idia of my toy is I want to have form containet where I am going to load form extantions and show them. I did this code:

My extantion :

using System.ComponentModel.Composition;
using System.Windows.Forms;

namespace MyExtantion
{
   
public interface IForm
   
{
       
void LoadForm(Form form);
   
}

   
[Export(typeof(IForm))]
   
public partial class MyExtantion : Form, IForm
   
{
       
public MyExtantion()
       
{
           
InitializeComponent();
       
}

       
public void LoadForm(Form form)
       
{
           
MdiParent = form;
           
Show();
       
}

   
}
}

and form container:

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Windows.Forms;

namespace FormsContainer
{
    public partial class FormContainer : Form
    {
        public FormContainer()
        {
            InitializeComponent();
        }

        private CompositionContainer _container;

        public interface IForm
        {
            void LoadForm(Form form);
        }

        [ImportMany(typeof(IForm))]
        public IEnumerable<IForm> Forms { get; set; }
       
        private bool Compose()
        {
            var catalog = new AggregateCatalog(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                new DirectoryCatalog("Extantions"));
            var batch = new CompositionBatch();
            batch.AddPart(this);

            _container = new CompositionContainer(catalog);

            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                return false;
            }

            return true;
        }

        private void FormContainer_Load(object sender, EventArgs e)
        {
            if (Compose())
                foreach (IForm form in Forms)
                {
                    form.LoadForm(this);
                }
        }

    }
}

The problem is I can not load my extantion I think because I do not have any imported Form.
I would be so glad if anybode enlighten me How I can achive it with MEF ? and What I do wrong ?.

 

 

Oct 19, 2010 at 7:12 AM

The solution for this issue is here http://stackoverflow.com/questions/3890266/mef-how-to-load-a-winform-into-winfrom-container