Обработка события изменения размера для пользовательского столбца DataGridView

#c# #.net #datagridview #resize

#c# #.net #datagridview #изменение размера

Вопрос:

Я попытался реализовать свой собственный пользовательский столбец DataGridView. Я сделал это, используя следующий код. Заимствование и изменение с этой страницы MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.idatagridvieweditingcontrol.aspx

Где я застрял, так это как уведомить usercontrol ucFolderBrowser о том, что размер gridviewcolumn был изменен и его необходимо соответствующим образом скорректировать?

 class FolderGridViewColumn : DataGridViewColumn
{
    public FolderGridViewColumn() : base(new FolderCell())
    {
    }

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

class FolderCell : DataGridViewTextBoxCell
{
    public FolderCell() : base()
    {
        //this.Style.Format = "";     //Can set format
    }

    public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
    {
        base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);

        FolderEditingControl ctl = DataGridView.EditingControl as FolderEditingControl;

        // Use the default row value when Value property is null.
        if (this.Value == null)
        {
            ctl.Text = (string)this.DefaultNewRowValue;
        }
        else
        {
            ctl.Text = (string)this.Value;
        }
    }
    public override Type EditType
    {
        get
        {
            // Return the type of the editing control that FolderCell uses.
            return typeof(FolderEditingControl);
        }
    }
    public override Type ValueType
    {
        get
        {
            // Return the type of the value that FolderBrowserCell contains.

            return typeof(string);
        }
    }
    public override object DefaultNewRowValue
    {
        get
        {
            //default value.
            return string.Empty;
        }
    }
}

class FolderEditingControl : ucFolderBrowser, IDataGridViewEditingControl
{
    DataGridView dataGridView;
    private bool valueChanged = false;
    int rowIndex;

    public FolderEditingControl() { }

    // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
    // property.
    public object EditingControlFormattedValue
    {
        get
        {
            return this.Text;
        }
        set
        {             
            this.Text = (string) value;
        }
    }

    // Implements the 
    // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
    public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
    {
        return this.EditingControlFormattedValue;
    }

    // Implements the 
    // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
    public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
    {
        this.Font = dataGridViewCellStyle.Font;
        this.ForeColor = dataGridViewCellStyle.ForeColor;
        this.BackColor = dataGridViewCellStyle.BackColor;
    }

    // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
    // property.
    public int EditingControlRowIndex
    {
        get
        {
            return rowIndex;
        }
        set
        {
            rowIndex = value;
        }
    }

    // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
    // method.
    public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
    {
        // Let the textbox handle the keys listed.
        switch (key amp; Keys.KeyCode)
        {
            case Keys.Left:
            case Keys.Right:
            case Keys.Home:
            case Keys.End:
            default:
                return !dataGridViewWantsInputKey;
        }
    }

    // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
    // method.
    public void PrepareEditingControlForEdit(bool selectAll)
    {
        // No preparation needs to be done.
    }

    // Implements the IDataGridViewEditingControl
    // .RepositionEditingControlOnValueChange property.
    public bool RepositionEditingControlOnValueChange
    {
        get
        {
            return false;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingControlDataGridView property.
    public DataGridView EditingControlDataGridView
    {
        get
        {
            return dataGridView;
        }
        set
        {
            dataGridView = value;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingControlValueChanged property.
    public bool EditingControlValueChanged
    {
        get
        {
            return valueChanged;
        }
        set
        {
            valueChanged = value;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingPanelCursor property.
    public Cursor EditingPanelCursor
    {
        get
        {
            return base.Cursor;
        }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        // Notify the DataGridView that the contents of the cell
        // have changed.
        valueChanged = true;
        this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
        base.OnTextChanged(e);
    }
}

public partial class ucFolderBrowser : UserControl
{
    public ucFolderBrowser()
    {
        InitializeComponent();
    }

    public override string Text
    {
        get
        {
            return txtPath.Text;
        }
        set
        {
            txtPath.Text = value;
        }
    }

    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.txtPath = new System.Windows.Forms.TextBox();
        this.btnBrowse = new System.Windows.Forms.Button();
        this.SuspendLayout();
        // 
        // txtPath
        // 
        this.txtPath.Location = new System.Drawing.Point(0, 0);
        this.txtPath.Name = "txtPath";
        this.txtPath.Size = new System.Drawing.Size(100, 20);
        this.txtPath.TabIndex = 0;
        // 
        // btnBrowse
        // 
        this.btnBrowse.Location = new System.Drawing.Point(100, -1);
        this.btnBrowse.Name = "btnBrowse";
        this.btnBrowse.Size = new System.Drawing.Size(30, 21);
        this.btnBrowse.TabIndex = 1;
        this.btnBrowse.Text = "...";
        this.btnBrowse.UseVisualStyleBackColor = true;
        this.btnBrowse.Click  = new System.EventHandler(this.btnBrowse_Click);
        // 
        // ucFolderBrowser
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Controls.Add(this.btnBrowse);
        this.Controls.Add(this.txtPath);
        this.Name = "ucFolderBrowser";
        this.Size = new System.Drawing.Size(129, 20);
        this.ResumeLayout(false);
        this.PerformLayout();

    }
}
  

Комментарии:

1. Вы имеете в виду, что хотите изменить размер самого usercontrol на основе изменения размера сетки?

2. Правильно! Очевидно, что иногда столбцы меняют размеры, поэтому я хочу получать уведомления и соответствующим образом обрабатывать событие.

Ответ №1:

Итак, оказывается, что решение заключается в использовании события изменения размера usercontrols — это событие срабатывает при изменении размера столбца DataGridView.

Затем я понял, что мне даже не нужно обрабатывать событие изменения размера, потому что я все равно могу закрепить оба моих элемента управления.