Ejemplo n.º 1
0
        /// <summary>
        /// stretch the columns width to always fit the available space when the contents of the cell is smaller.
        /// </summary>
        public virtual void StretchToFit()
        {
            SuspendLayout();

            Rectangle displayRect = Grid.DisplayRectangle;

            int?firstVisible = Grid.GetFirstVisibleScrollableColumn();

            if (Count > 0 && displayRect.Width > 0)
            {
                List <int> visibleIndex = ColumnsInsideRegion(firstVisible, displayRect.X, displayRect.Width);

                //Continue only if the columns are all visible, otherwise this method cannot shirnk the columns
                if (visibleIndex.Count >= Count)
                {
                    int?current = GetRight(firstVisible, Count - 1);
                    if (current != null && displayRect.Width > current.Value)
                    {
                        //Calculate the columns to stretch
                        int countToStretch = 0;
                        for (int i = 0; i < Count; i++)
                        {
                            if ((GetAutoSizeMode(i) & AutoSizeMode.EnableStretch) == AutoSizeMode.EnableStretch)
                            {
                                countToStretch++;
                            }
                        }

                        int deltaPerColumn = (displayRect.Width - current.Value) / countToStretch;
                        for (int i = 0; i < Count; i++)
                        {
                            if ((GetAutoSizeMode(i) & AutoSizeMode.EnableStretch) == AutoSizeMode.EnableStretch)
                            {
                                SetWidth(i, GetWidth(i) + deltaPerColumn);
                            }
                        }
                    }
                }
            }

            ResumeLayout();
        }