如何在DataGridView中添加自定义控件(LedLight)? [英] How to add a Custom Control(LedLight) in DataGridView?

查看:89
本文介绍了如何在DataGridView中添加自定义控件(LedLight)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个名为LedLight的自定义控件,该控件继承了System.Windows.Forms.UserControl,并且必须将此控件添加到DataGridView列中.
我已经为自定义控件编写了以下代码.

Hi
I have a custom control named LedLight which inherits the System.Windows.Forms.UserControl and I have to add this control to DataGridView column.

I have written follwing code for my custom control.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace LedLight
{
    public partial class Led : UserControl
    {
        private Timer tick;
        public Led()
            : base()
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.DoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.ResizeRedraw, true);

            Width = 17;
            Height = 17;

            Paint += new PaintEventHandler(Led_Paint);

            tick = new Timer();
            tick.Enabled = false;
            tick.Tick += new EventHandler(tick_Tick);
            InitializeComponent();
        }

        #region Properties

        /// <summary>
        /// To Indicate whether it is Active 
        /// </summary>
        private bool _Active = true;
        [Category("Behavior"),
          DefaultValue(true)]
        public bool Active
        {
            get { return _Active; }
            set { _Active = value; }
        }


        /// <summary>
        /// Set the Color on
        /// </summary>
        private Color _ColorOn = Color.Red;
        [Category("Appearance")]
        public Color ColorOn
        {
            get { return _ColorOn; }
            set { _ColorOn = value; Invalidate(); }
        }


        /// <summary>
        /// Set the Color Off.
        /// </summary>
        private Color _ColorOff = SystemColors.Control;
        [Category("Appearance")]
        public Color ColorOff
        {
            get { return _ColorOff; }
            set { _ColorOff = value; Invalidate(); }
        }


        /// <summary>
        /// To set the Flash property
        /// </summary>
        private string _FlashIntervals = "250";
        [Category("Appearance"),
         DefaultValue("250")]
        public int[] flashIntervals = new int[1] { 250 };
        public string FlashIntervals
        {
            get { return _FlashIntervals; }
            set
            {
                _FlashIntervals = value;
                string[] fi = _FlashIntervals.Split(new char[] { '','', ''/'', ''|'', '' '', ''\n'' });
                flashIntervals = new int[fi.Length];
                for (int i = 0; i < fi.Length; i++)
                    try
                    {
                        flashIntervals[i] = int.Parse(fi[i]);
                    }
                    catch
                    {
                        flashIntervals[i] = 25;
                    }
            }
        }



        /// <summary>
        /// To set the Flash property
        /// </summary>
        private string _FlashColors = string.Empty;
        [Category("Appearance"),
         DefaultValue("")]
        public Color[] flashColors;
        public string FlashColors
        {
            get { return _FlashColors; }
            set
            {
                _FlashColors = value;
                if (_FlashColors == string.Empty)
                {
                    flashColors = null;
                }
                else
                {
                    string[] fc = _FlashColors.Split(new char[] { '','', ''/'', ''|'', '' '', ''\n'' });
                    flashColors = new Color[fc.Length];
                    for (int i = 0; i < fc.Length; i++)
                        try
                        {
                            flashColors[i] = (fc[i] != "") ? Color.FromName(fc[i]) : Color.Empty;
                        }
                        catch
                        {
                            flashColors[i] = Color.Empty;
                        }
                }
            }
        }


        /// <summary>
        /// To set the Flash property
        /// </summary>
        private bool _Flash = false;
        [Category("Behavior"),
         DefaultValue(false)]
        public bool Flash
        {
            get { return _Flash; }
            set
            {
                _Flash = value && (flashIntervals.Length > 0);
                tickIndex = 0;
                tick.Interval = flashIntervals[tickIndex];
                tick.Enabled = _Flash;
                Active = true;
            }
        }

        #endregion

        #region helper color function

        private static Color FadeColor(Color c1, Color c2, int i1, int i2)
        {
            int r = (i1 * c1.R + i2 * c2.R) / (i1 + i2);
            int g = (i1 * c1.G + i2 * c2.G) / (i1 + i2);
            int b = (i1 * c1.B + i2 * c2.B) / (i1 + i2);

            return Color.FromArgb(r, g, b);
        }

        public static Color FadeColor(Color c1, Color c2)
        {
            return FadeColor(c1, c2, 1, 1);
        }

        #endregion

        /// <summary>
        /// Fires after every specified interval of time.
        /// </summary>

        public int tickIndex;
        void tick_Tick(object sender, EventArgs e)
        {
            tickIndex = (++tickIndex) % (flashIntervals.Length);
            tick.Interval = flashIntervals[tickIndex];
            try
            {
                if ((flashColors == null)
                || (flashColors.Length < tickIndex)
                || (flashColors[tickIndex] == Color.Empty))
                    Active = !Active;
                else
                {
                    ColorOn = flashColors[tickIndex];
                    Active = true;
                }
            }
            catch
            {
                Active = !Active;

            }
        }

        /// <summary>
        /// paints the LED lights
        /// </summary>
        void Led_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(BackColor);
            if (Enabled)
            {
                if (Active)
                {
                    e.Graphics.FillEllipse(new SolidBrush(ColorOn), 1, 1, Width - 3, Height - 3);
                    e.Graphics.DrawArc(new Pen(FadeColor(ColorOn, Color.White, 1, 2), 2), 3, 3, Width - 7, Height - 7, -90.0F, -90.0F);
                    e.Graphics.DrawEllipse(new Pen(FadeColor(ColorOn, Color.Black), 1), 1, 1, Width - 3, Height - 3);
                }
                else
                {
                    e.Graphics.FillEllipse(new SolidBrush(ColorOff), 1, 1, Width - 3, Height - 3);
                    e.Graphics.DrawArc(new Pen(FadeColor(ColorOff, Color.Black, 2, 1), 2), 3, 3, Width - 7, Height - 7, 0.0F, 90.0F);
                    e.Graphics.DrawEllipse(new Pen(FadeColor(ColorOff, Color.Black), 1), 1, 1, Width - 3, Height - 3);
                }
            }
            else
            {
                e.Graphics.DrawEllipse(new Pen(System.Drawing.SystemColors.ControlDark, 1), 1, 1, Width - 3, Height - 3);
            }
        }

        private void Led_Load(object sender, EventArgs e)
        {

        }
    }



我为Column编写的以下代码.



The following code I have written for Column.

public class LedColumn : DataGridViewColumn
{
    public LedColumn()
        : base()
    {

        new Led();
    }

    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            //Ensure that the cell used for the Template is a Led cell.
            if (value != null && !value.GetType().IsAssignableFrom(typeof(LedCell)))
            {
                throw new InvalidCastException("Must be a Led cell.");
            }
            base.CellTemplate = value;
        }
    }
    }



这是Cell的代码.



This is the code for Cell.

public class LedCell : DataGridViewCell
      {
          public LedCell()
              : base()
          {

          }


          protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
          {
              return value;
          }

          public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
          {
              // Set the value of the editing control to the current cell value.
              base.InitializeEditingControl(rowIndex, initialFormattedValue,
                  dataGridViewCellStyle);
              LedEditingControl ctl = DataGridView.EditingControl as LedEditingControl;

              // Use the default row value when Value property is null.

              //Use Default Row when the Property is null.
              if (this.Value == null)
              {
            //    ctrl.Value = (Led)this.DefaultNewRowValue;
              }
              else
              {
                //  ctrl.Value = (Led)this.Value;
              }
          }

          public override Type EditType
          {
              get
              {
                  //Returns the Type of Editing control that Ledcell uses.
                  return null;
              }
          }

          public override Type ValueType
          {
              get
              {
                  // Return the Type of value that the LedCell contains
                  return typeof(System.Object);
              }
          }



          public override object DefaultNewRowValue
          {
              get
              {
                  //Use Led as Default Value.
                  return new Led();
              }
          }
      }



而且,这是用于编辑控件



And, This is for editing Control

class LedEditingControl : Led,IDataGridViewEditingControl
{
    DataGridView dataGridView;
    int rowIndex;
    private bool valueChanged = false;


    public LedEditingControl()
    {
    }

    #region IDataGridViewEditingControl Members

    public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
    {
        this.Font = dataGridViewCellStyle.Font;
    }

    public DataGridView EditingControlDataGridView
    {
        get
        {
            return dataGridView;
        }
        set
        {
            dataGridView = value;
        }
    }

    public object EditingControlFormattedValue
    {
        get
        {
            return typeof(System.Object);
        }
        set
        {
            if (value is LedCell)
            {

            }
        }
    }

    public int EditingControlRowIndex
    {
        get
        {
            return rowIndex;
        }
        set
        {
            rowIndex = value;
        }
    }

    public bool EditingControlValueChanged
    {
        get
        {
            return valueChanged;
        }
        set
        {
            valueChanged = value;
        }
    }

    public bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey)
    {
        return !dataGridViewWantsInputKey;
    }

    public Cursor EditingPanelCursor
    {
        get { return Cursor; }
    }

    public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
    {
        return EditingControlFormattedValue;
    }

    public void PrepareEditingControlForEdit(bool selectAll)
    {

    }

    public bool RepositionEditingControlOnValueChange
    {
        get { return false; }
    }

    #endregion
}

}



请在这里的任何人都可以帮助我.

在此先感谢.



Plz any one here can help me.

Thanks in advance.

推荐答案

如果是自定义控件,则在编译类库时将创建一个DLL.在Visual Studio工具箱中添加该控件,该控件将作为其他标准控件出现在页面设计器中.

您无需添加任何特定于自定义控件的代码即可使用它.
If it is a custom control then a DLL would have been created on compiling the class library. Add that in your Visual Studio toolbox and the control would appear as other standard controls to be drag-dropped on the page designer.

You don''t need to add any custom-control specific code as such to use it.


数据网格仅托管当前可编辑单元格中的控件.在其他任何地方,它仅通过调用DataGridViewCell.Paint绘制单元格内容.您需要创建自定义列和单元格类型,而不是自定义控件.我不确定何时调用Paint,闪烁的灯光可能更难实现–无论如何,它们不太可能是在数据网格中的良好用户体验.
The data grid only hosts controls within the currently editable cell. Everywhere else, it just paints the cell contents, by calling DataGridViewCell.Paint. You need to create a custom column and cell type, not a custom control. I''m not sure when Paint gets called, flashing lights may be more difficult to achieve – they''re not likely to be a good user experience in a data grid anyway.


这篇关于如何在DataGridView中添加自定义控件(LedLight)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆