【问题标题】:How to add an extended control to the toolbox, when the control is in the same project?当控件在同一个项目中时,如何将扩展控件添加到工具箱中?
【发布时间】:2018-03-14 22:44:40
【问题描述】:

我已扩展DataGridView。我想将新控件添加到工具箱而不添加对不同程序集的引用(使用右键单击选项“选择项目”)。控件在表单的同一个项目中,我不想将它们分开。我怎样才能做到这一点?

谢谢。

编辑:如果不是用户控件,这不可能与有关用户控件的问题重复。

编辑 2: 代码本身(正在进行中。尚未完成):

class BindedDataGrid<T> : DataGridView
{
    public BindedDataGrid()
    {
        InitializeComponent();

        IEnumerable<PropertyInfo> properties = typeof(T).GetProperties().Where(p => Attribute.IsDefined(p, typeof(BindingValueAttribute)));

        foreach (PropertyInfo property in properties)
        {
            var column = new DataGridViewColumn()
            {
                HeaderText = ((property.GetCustomAttributes(true)[0]) as BindingValueAttribute).Value
            };

            Columns.Add(column);
        }
    }
}

【问题讨论】:

  • 嗯。它应该被定义为项目组件之一。显示在 ProjectName_Components 选项卡中。您的扩展继承自 UserControl ?
  • @o_O - 这个问题是关于扩展控件,而不是用户控件。
  • 我的错,this might help u
  • @Z.R.T. - 没有。我在哪里可以看到“组件”标签?
  • 是的,这是个问题。设计师无法选择 T。

标签: c# winforms visual-studio controls toolbox


【解决方案1】:
public class BindedDataGrid : DataGridView
    {
        public BindedDataGrid()
        {
        }

        public BindedDataGrid(Type bindType)
        {
            IEnumerable<PropertyInfo> properties = bindType.GetProperties().Where(p => Attribute.IsDefined(p, typeof(BindingValueAttribute)));

            foreach (PropertyInfo property in properties)
            {
                var prop = property.GetCustomAttributes(true)[0];
                if (prop is BindingValueAttribute)
                {
                    var column = new DataGridViewColumn()
                    {
                        HeaderText = property.Name
                    };
                    column.CellTemplate = new DataGridViewTextBoxCell();
                    Columns.Add(column);
                }
            }
        }
    }

    public class BindingValueAttribute  : Attribute
    {
        public string Value { get; set; }
    }

    public class BindOne
    {
        [BindingValueAttribute()]
        public string Name { get; set; }

        [BindingValueAttribute()]
        public int Age { get; set; }
    }
  1. 首先使 BindedDataGrid 不是通用的
  2. 创建一个非参数化的构造函数

        private void InitializeComponent()
    {
        this.bindedDataGrid1 = new PlayingWithThread.BindedDataGrid(typeof(BindOne));
        ((System.ComponentModel.ISupportInitialize)(this.bindedDataGrid1)).BeginInit();
    

【讨论】:

    猜你喜欢
    • 2014-03-20
    • 2021-09-05
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    相关资源
    最近更新 更多