2017-01-08 61 views
0

我想創建一個控件,在類庫項目中繪製一個表格,並將此dll添加到工具箱中,並在Windows窗體應用程序中使用它。我嘗試和谷歌搜索,但我找不到。 我該怎麼辦?如何在Visual Studio 2015中創建自定義控件並將其添加到工具箱

我在類庫項目

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Drawing; 
using System.Data; 
using System.Windows.Forms; 
namespace ClassLibrary1 
{ 
class PanelZ : System.Windows.Forms.Panel 
{ 
    private Color color1 = Color.SteelBlue; 
    private Color color2 = Color.DarkBlue; 
    private int color1Transparent = 150; 
    private int color2Transparent = 150; 
    private int angle = 90; 

    public Color StartColor 
    { 
     get { return color1; } 
     set { color1 = value; Invalidate(); } 
    } 
    public Color EndColor 
    { 
     get { return color2; } 
     set { color2 = value; Invalidate(); } 
    } 
    public int Transparent1 
    { 
     get { return color1Transparent; } 
     set 
     { 
      color1Transparent = value; 
      if (color1Transparent > 255) 
      { 
       color1Transparent = 255; 
       Invalidate(); 
      } 
      else 
       Invalidate(); 
     } 
    } 

    public int Transparent2 
    { 
     get { return color2Transparent; } 
     set 
     { 
      color2Transparent = value; 
      if (color2Transparent > 255) 
      { 
       color2Transparent = 255; 
       Invalidate(); 
      } 
      else 
       Invalidate(); 
     } 
    } 

    public int GradientAngle 
    { 
     get { return angle; } 
     set { angle = value; Invalidate(); } 
    } 
    public PanelZ() 
    { 
    } 
    protected override void OnPaint(PaintEventArgs e) 
    { 
     base.OnPaint(e); 
     Color c1 = Color.FromArgb(color1Transparent, color1); 
     Color c2 = Color.FromArgb(color2Transparent, color2); 
     Brush b = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, c1, c2, angle); 
     e.Graphics.FillRectangle(b, ClientRectangle); 
     b.Dispose(); 
    } 
} 

}

創建此類但是當我添加MYDLL到工具箱中我得到這個錯誤 image here

回答

2

在WPF或的WinForms工具箱是聰明組件是您正在構建的解決方案的一部分。對於Winforms,只需將System.Windows.FormsSystem.Drawing的引用添加到您的類庫中,然後從Control(或繼承自Control的任何其他類)繼承。

例如,我可以創建這樣一個自定義的控制(請注意,它必須是一個公共控制工具箱中找到它):

using System.Drawing; 
using System.Windows.Forms; 

namespace ClassLibrary1 
{ 
    public class CustomControl : Control 
    { 
     public CustomControl() 
     { 
      this.BackColor = Color.Red; 
     } 
    } 
} 

一旦我生成項目,然後我就可以看到它在工具箱中與我的應用程序中的表單交互時。

enter image description here

+0

我可以在類庫項目中創建它,並將此dll添加到工具箱? – zfarzaneh

+0

如果它們在單獨的解決方案中,則可以使用工具箱中的右鍵單擊菜單,選擇「選擇項目」並瀏覽到DLL,將其添加到工具箱中。 –

+0

我更新了答案,指出錯誤的原因。它需要是一個「公共」控制 –

相關問題