簡體   English   中英

動態加載的dll接口函數返回usercontrol

[英]Dynamically loaded dll interface function returns usercontrol

對於一個小項目,我創建了一個用於創建插件的基本界面。 此接口具有返回UserControl的函數。 但是,當調用它並將UserControl添加到面板時,面板中不會顯示任何內容(即使設置了.Show()Visibility = true )。 我假設當調用assembly.CreateInstance()時,這會創建類中任何對象的實例。

這不是這種情況嗎? 是否需要在所有UserControl上調用CreateInstance()才能以這種方式使用它們?

public interface IMyInterface
{
    System.Windows.Forms.UserControl GetConfigurationControl();
}

在dll中實現了類:

public class myClass: IMyInterface
{
    return new myUserControl();
}

加載目錄中的所有dll:

private void LoadPlugins()
{
 foreach (string file in Directory.GetFiles(Application.StartupPath+"/plugins/", "*.dll",       SearchOption.AllDirectories))
        {
            Assembly assembly = Assembly.LoadFile(file);
            var types = from t in assembly.GetTypes()
                    where t.IsClass &&
                    (t.GetInterface(typeof(IMyInterface).Name) != null)
                    select t;
            foreach (Type t in types)
            {
                IMyInterface plugin = (IMyInterface)assembly.CreateInstance(t.FullName, true);
                this.pluginsList.Add(plugin); //just a list of the plugins
            }
        }
    this.AddPluginUserControls();
 }    

將用戶控件添加到面板:

 private AddPluginUserControls()
 {
     foreach (IMyInterface plugin in pluginsList)
     {
          myPanel.Controls.Add(plugin.GetConfigurationControl());
     }
 }

我知道其他完整的插件架構,但這更像是一個學習應用程序。 謝謝!

用戶控件:

public partial class myUserControl: UserControl
{
    public myUserControl()
    {
        InitializeComponent(); // couple of labels, vs generated.
    }
}

確保兩件事1.在默認的myUserControl構造函數中,調用InitializeComponent(),它將實例化並將標簽添加到控件中。 2.在添加到面板之前,為用戶控件提供一些寬度和高度。

找到了吧! 使用System.Windows.Forms.FlowLayoutPanel和將DockStyle設置為填充的UserControl是一個問題。 謝謝你的回答!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM