с# Создание собственного элемента управления (компонента) - -пример кода
Primary tabs
Forums:
Фрагмент из проекта:
using System; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; //добавляем это чтобы работать с DesignerActionList и вообще - ActionList using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; // это пришлось подключить самостоятельно. using System.Windows; namespace WindowsFormsApplication1 { // [DefaultProperty("StartColor")] [Designer(typeof(ExampleComponentDesigner))] // [DesignerAttribute( "thfth" )] public class myComponent : UserControl { // public myComponent() // { //// InitializeComponent(); // } private void myComponent_Load(object sender, EventArgs e) { } protected override void OnPaint(PaintEventArgs pe) { Graphics g = pe.Graphics; //LinearGradientMode myMode = new LinearGradientMode() ; switch (BrushType) { case bbrushType.LinearGradientBrush: Brush brush0 = new LinearGradientBrush(ClientRectangle, this.StartColor, this.EndColor, LinearGradientMode.Vertical); g.FillRectangle(brush0, ClientRectangle); break; case bbrushType.SolidColorBrush: Brush brush1 = new SolidBrush(this.MainColor); g.FillRectangle(brush1, ClientRectangle); break; } //------------------ далее выводим текст g.DrawString(" +ЭТО КОМПОНЕНТ+", Font, Brushes.Black, 10, this.Height / 2); base.OnPaint(pe); } // цвета, используемые при раскраске контрола - видимого компонента. private Color startColor; private Color endColor; private Color mainColor; private bbrushType brushType; [Bindable(true), Category("BrushOptions"), Description("Цвет начала заливки"), DefaultValue(typeof(Color), "Color.Green")] public Color StartColor { get { return startColor; } set { startColor = value; OnChangeProperties(); } } [Bindable(true), Category("BrushOptions"), Description("Цвет конца заливки"), DefaultValue("Color.White")] public Color EndColor { get { return endColor; } set { endColor = value; OnChangeProperties(); } } [DefaultValue("Color.Red")] public Color MainColor { get { return mainColor; } set { mainColor = value; OnChangeProperties(); } } [Bindable(true), Category("BrushOptions"), Description(" Тип кисти"), DefaultValue(typeof(Brush), "LinearGradientBrush")] public bbrushType BrushType { get { return brushType; } set { brushType = value; OnChangeProperties(); } } public void OnChangeProperties() { Invalidate(); } } // [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] public class ExampleComponentDesigner : System.Windows.Forms.Design.ControlDesigner { private DesignerActionListCollection actionList; public override DesignerActionListCollection ActionLists //буква s в конце имени этого метода важна.....очень...-долго же я сравнивал свой метод и msdn-вский -я даже не написал что мой оверрайд - и ошибку тоже не получил , так как исхлдный метод другой оказывается. { get { if (null == actionList) { actionList = new DesignerActionListCollection(); actionList.Add(new myActionList(this.Component)); } return actionList; } } } //-----------------------------далее ActionList - public class myActionList : System.ComponentModel.Design.DesignerActionList { private DesignerActionUIService designerActionUISvc = null; myComponent mcom; // конструктор public myActionList(IComponent component): base(component) { mcom = component as myComponent; // сохраняем ссылку на компонент this.designerActionUISvc = GetService(typeof(DesignerActionUIService)) as DesignerActionUIService; } // добавим тегу свойства // Элементы компонента, выносимые в диалог смарт-тега public Color StartColor { get { return this.mcom.StartColor; } set { this.GetPropertyByName("StartColor").SetValue(mcom, value); } } public Color EndColor { get { return this.mcom.EndColor; } set { this.GetPropertyByName("EndColor").SetValue(mcom, value); } } public Color MainColor { get { return this.mcom.MainColor; } set { this.GetPropertyByName("MainColor").SetValue(mcom, value); } } public bbrushType BrushType { get { return this.mcom.BrushType; } set { this.GetPropertyByName("BrushType").SetValue(mcom, value); } } public void InvertColors() // поменяем цвета местами. { Color tmp = mcom.StartColor; StartColor = mcom.EndColor; EndColor = tmp; // далее чтобы не только перекрасился компонент, но и произошло обновление данных смарт тега вызываем его обновление = designerActionUISvc.Refresh(mcom); } private PropertyDescriptor GetPropertyByName(string propName) { PropertyDescriptor prop; prop = TypeDescriptor.GetProperties(mcom)[propName]; if (null == prop) { throw new ArgumentException("Указаное свойство не найдено.", propName); } else { return prop; } } public override DesignerActionItemCollection GetSortedActionItems() { DesignerActionItemCollection items = new DesignerActionItemCollection(); //Define static section header entries. items.Add(new DesignerActionHeaderItem("Цвета")); items.Add(new DesignerActionHeaderItem("Опции кисти")); switch (BrushType) { case bbrushType.LinearGradientBrush : break; } items.Add(new DesignerActionPropertyItem("StartColor", "Начало:", "Цвета", "ВЫберите цвет начала градиента.")); items.Add(new DesignerActionPropertyItem("EndColor", "Завершение:", "Цвета", "ВЫберите цвет завершения градиента.")); items.Add(new DesignerActionPropertyItem("MainColor", "Основной цвет:", "Цвета", "Выберите цвет для обычной заливки компонента.")); items.Add(new DesignerActionMethodItem(this,"InvertColors", "Обратить цвета", "Цвета", "Меняет цвета начала и завершения градиента местами", true)); items.Add(new DesignerActionPropertyItem("BrushType", "Тип кисти:", "Опции кисти", "ВЫберите цвет завершения градиента.")); return items; } } //--------------далее вспомогательные классы----------------- /* Как можно сделать перечислимый тип видимым в нескольких классах * если перечислимый тип не видим то - enum * перечислимый тип в си шарп можно определить за пределами класса и тогда он будет виден.*/ public enum bbrushType // это просто перечислимый кисть - в соответствии с одним из значений мы будем раскрашивать компонент и изменять смарт-тэг. { LinearGradientBrush = 0, SolidColorBrush = 1 } }
- Log in to post comments
- 3129 reads