Exemplo n.º 1
0
        public void DoubleToDataGridLengthConverterConvertBackTest()
        {
            var            cvt = new DoubleToDataGridLengthConverter();
            DataGridLength l   = DataGridLength.Auto;

            double v = (double)cvt.ConvertBack(l, typeof(int), null, System.Globalization.CultureInfo.CurrentCulture);
        }
Exemplo n.º 2
0
        public GittiupDataGrid()
        {
            // Styles don't automatically apply to subclasses, so we have to force the issue
            Style = (Style)FindResource(typeof(DataGrid));

            SelectionMode = DataGridSelectionMode.Single;
            SelectionUnit = DataGridSelectionUnit.FullRow;

            // This is a hack to fix a bug in DataGrid where in many scenarios it fails to accurately calculate
            // the width of the columns and gives too much width to * columns.  This hack uses the LayoutUpdated
            // event to track for the first time when the column's width has changed from the default value of the
            // MinWidth.  At that point, we can reset the Width to zero and back, and finally the column widths
            // will be calculated accurately.
            void OnLayoutUpdated(object sender, EventArgs args)
            {
                foreach (DataGridColumn column in Columns.Where(x => x.Width.IsStar))
                {
                    if (column.ActualWidth != column.MinWidth)
                    {
                        DataGridLength width = column.Width;
                        column.Width   = 0;
                        column.Width   = width;
                        LayoutUpdated -= OnLayoutUpdated;
                    }
                }
            }

            LayoutUpdated += OnLayoutUpdated;
        }
Exemplo n.º 3
0
        internal static void UpdateGridColumnWidth(DataGridColumn column)
        {
            DataGridLength newValue = column.Width;

            if (column._parent != null && INTERNAL_VisualTreeManager.IsElementInVisualTree(column._parent))
            {
                GridUnitType newGridUnitType;
                switch (newValue.UnitType)
                {
                case DataGridLengthUnitType.Auto:
                    newGridUnitType = GridUnitType.Auto;
                    break;

                case DataGridLengthUnitType.Pixel:
                    newGridUnitType = GridUnitType.Pixel;
                    break;

                case DataGridLengthUnitType.Star:
                    newGridUnitType = GridUnitType.Star;
                    break;

                //case DataGridLengthUnitType.SizeToCells:
                //    //todo: probably Auto
                //    break;
                //case DataGridLengthUnitType.SizeToHeader:
                //    //todo: probably Auto
                //    break;
                default:
                    newGridUnitType = GridUnitType.Auto;
                    break;
                }
                column._gridColumn.Width = new GridLength(newValue.Value, newGridUnitType);
            }
        }
 private static void UpdateColumnWidths(ICollection <DataGridColumn> columns, DataGridLength width)
 {
     foreach (var column in columns)
     {
         column.Width = width;
     }
 }
Exemplo n.º 5
0
        private void initSignalSourceGrid()
        {
            this.SignalSourceGrid.Columns.Clear();

            DataGridLength length = new DataGridLength(1, DataGridLengthUnitType.Star);

            this.SignalSourceGrid.Columns.Add(new DataGridTextColumn()
            {
                Header     = "时段\\日期",
                Binding    = new Binding("ClinicVistTime.Shift.Name"),
                Width      = 63,
                IsReadOnly = true
                             //,
                             //Foreground = Brushes.Blue // 设置该列字体颜色
            });

            for (int i = 0; i < 7; i++)
            {
                DateTime tempDate = DateTime.Now.AddDays(i);
                this.SignalSourceGrid.Columns.Add(new DataGridTextColumn()
                {
                    Header     = tempDate.ToString("yyyy-MM-dd dddd"),
                    Binding    = new Binding("weekStringList[" + (int)tempDate.DayOfWeek + "]"),
                    Width      = length,
                    IsReadOnly = (tempDate.Date >= DateTime.Now.Date ? false : true)
                });
            }
        }
Exemplo n.º 6
0
 public static void BuildServiceColumns(BatchLine line, DataGrid grid)
 {
     if (line == null)
     {
         return;
     }
     grid.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
     foreach (var pair in line.ParsedServiceFields.Where(k => k.Key != "ReportData"))
     {
         var key = pair.Key;
         //todo - хорошо бы вычислять ширину колонок, но непонятно как
         //если задать с помощью звезды колонка будет зажата в минимальный размер
         //тк все имеющееся пространство уже будет распределено между фиксированными колонками
         //var width = new DataGridLength(1, DataGridLengthUnitType.Star);
         var width = new DataGridLength(50, DataGridLengthUnitType.Pixel);
         grid.Columns.Add(new DataGridTextColumn {
             Width   = width,
             Header  = key,
             Binding = new Binding(".")
             {
                 Converter = new LambdaConverter <BatchLine>(l => l?.ParsedServiceFields.GetValueOrDefault(key),
                                                             o => {
                     return((o as BatchLineView).BatchLine);
                 })
             }
         });
     }
 }
        private void MapSeatData(List <FlightSeatInfo> seatInfos, SeatClass seatClass, DataGrid dataGrid)
        {
            var seats          = seatInfos.Where(s => s.SeatClass == seatClass).FirstOrDefault()?.SeatMatrix;
            var dataGridLength = new DataGridLength(seats.Length, DataGridLengthUnitType.Star);

            dataGrid.ItemsSource = GenerateDataTableForSeat(seats);
            dataGrid.ColumnWidth = dataGridLength;
        }
Exemplo n.º 8
0
 private void RestoreLastColumn()
 {
     if (lastColumn != null)
     {
         lastColumn.Width      = lastColumnWidthBackup;
         lastColumn            = null;
         lastColumnWidthBackup = default(DataGridLength);
     }
 }
Exemplo n.º 9
0
        static public void ColumnResize(this DataGrid dg, string sName, DataGridLength stDGL)
        {
            DataGridColumn dgcColumn;

            if (null != (dgcColumn = dg.ColumnGet(sName)))
            {
                dgcColumn.Width = stDGL;
            }
        }
 private void AssociatedObjectSizeChanged(object sender, SizeChangedEventArgs e)
 {
     foreach (DataGridColumn dataGridColumn in AssociatedObject.Columns)
     {
         DataGridLength dataGridLength = dataGridColumn.Width;
         dataGridColumn.ClearValue(DataGridColumn.WidthProperty);
         dataGridColumn.Width = dataGridLength;
     }
 }
Exemplo n.º 11
0
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null || !(value is GridLength))
            {
                return(DataGridLength.Auto);
            }
            var result = new DataGridLength(((GridLength)value).Value);

            return(result);
        }
        public static void RotateButtonImage(Button showId, DataGridLength width)
        {
            showId.RenderTransformOrigin = new Point(0.5, 0.5);
            ScaleTransform flipTrans = new ScaleTransform
            {
                ScaleX = width.UnitType == DataGridLengthUnitType.SizeToCells ? 1 : -1
            };

            showId.RenderTransform = flipTrans;
        }
Exemplo n.º 13
0
        public void AdicionarDataGridColumn(string cabecalho, Binding binding, DataGridLength larguraColuna)
        {
            var dataGridColumn = new DataGridTextColumn
            {
                Header  = cabecalho,
                Binding = binding,
                Width   = larguraColuna
            };

            ColunasDataGrid.Add(dataGridColumn);
        }
Exemplo n.º 14
0
 public UIGridColumn(string header, string path, string stringFormat,
                     string tooltip, string tooltipPath, DataGridLength length, bool isRightAligned = false)
 {
     this.Header         = header;
     this.Path           = path;
     this.StringFormat   = stringFormat;
     this.Tooltip        = tooltip;
     this.TooltipPath    = tooltipPath;
     this.Length         = length;
     this.IsRightAligned = isRightAligned;
 }
Exemplo n.º 15
0
        private void MontarColunasDataGrid()
        {
            if (DataGrid.Columns.Count != 3)
            {
                return;
            }

            var starWidth = new DataGridLength(1.0, DataGridLengthUnitType.Star);

            if (!Model.BotaoOpcoes)
            {
                DataGrid.Columns.RemoveAt(0);
            }

            if (!Model.BotaoEditar && !Model.BotaoOpcoes)
            {
                DataGrid.Columns.RemoveAt(0);
            }

            if (!Model.BotaoEditar && Model.BotaoOpcoes)
            {
                DataGrid.Columns.RemoveAt(1);
            }

            if (!Model.BotaoDeletar && Model.BotaoOpcoes && Model.BotaoEditar)
            {
                DataGrid.Columns.RemoveAt(2);
            }

            if (!Model.BotaoDeletar && Model.BotaoOpcoes && !Model.BotaoEditar)
            {
                DataGrid.Columns.RemoveAt(1);
            }

            if (!Model.BotaoDeletar && !Model.BotaoOpcoes && Model.BotaoEditar)
            {
                DataGrid.Columns.RemoveAt(1);
            }

            if (!Model.BotaoDeletar && !Model.BotaoOpcoes && !Model.BotaoEditar)
            {
                DataGrid.Columns.RemoveAt(0);
            }

            foreach (var dataGridColumn in Model.ColunasDataGrid)
            {
                if (dataGridColumn.Width.IsAuto)
                {
                    dataGridColumn.Width = starWidth;
                }

                DataGrid.Columns.Add(dataGridColumn);
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Set one column width.
 /// </summary>
 /// <param name="_header">A string param.</param>
 /// <param name="_width">A DataGridLength param.</param>
 /// <returns>IMyDataGrid</returns>
 public IMyDataGrid setOneColumnWidth(string _header, DataGridLength _width)
 {
     foreach (DataGridColumn column in myDataGrid_dg.Columns)
     {
         if (_header.Equals(column.Header))
         {
             column.Width = _width;
         }
     }
     return(this);
 }
Exemplo n.º 17
0
        private void initDateClinicMsgGrid()
        {
            this.DateClinicMsgGrid.Columns.Clear();

            CommClient.WorkType           myd = new CommClient.WorkType();
            List <CommContracts.WorkType> listOfAllWorkTypes = myd.GetAllWorkType();
            DataGridLength length = new DataGridLength(1, DataGridLengthUnitType.Star);



            this.DateClinicMsgGrid.Columns.Add(new DataGridTextColumn()
            {
                Header     = "人员",
                Binding    = new Binding("Name"),
                Width      = 100,
                IsReadOnly = true
                             //,
                             //Foreground = Brushes.Blue // 设置该列字体颜色
            });

            this.DateClinicMsgGrid.Columns.Add(new DataGridTextColumn()
            {
                Header     = "时段",
                Binding    = new Binding("ShiftName"),
                Width      = 100,
                IsReadOnly = true
                             //,
                             //Foreground = Brushes.Blue // 设置该列字体颜色
            });

            for (int i = 0; i < 7; i++)
            {
                DateTime tempDate = getMonday(currentManageDate).AddDays(i);
                this.DateClinicMsgGrid.Columns.Add(new DataGridComboBoxColumn()
                {
                    Header = tempDate.ToString("yyyy-MM-dd dddd"),
                    SelectedItemBinding = new Binding("WorkPlanWorkTypeList[" + (int)tempDate.DayOfWeek + "]"),
                    ItemsSource         = listOfAllWorkTypes,
                    Width      = length,
                    IsReadOnly = (tempDate.Date >= DateTime.Now.Date ? false : true)
                });
            }

            this.DateClinicMsgGrid.Columns.Add(new DataGridTextColumn()
            {
                Header     = "最大工作量",
                Binding    = new Binding("MaxVistNum"),
                Width      = 100,
                IsReadOnly = false,
                Foreground = Brushes.Green // 设置该列字体颜色
            });
        }
Exemplo n.º 18
0
 private void AcquireLastColumn()
 {
     if (!IsEnabled)
     {
         return;
     }
     lastColumn = TargetDataGrid.Columns.LastOrDefault();
     if (lastColumn != null)
     {
         lastColumnWidthBackup = lastColumn.Width;
         lastColumn.Width      = new DataGridLength(100.0, DataGridLengthUnitType.Star);
     }
 }
Exemplo n.º 19
0
        private void setColumnsWidth()
        {
            DataGridLength length1   = new DataGridLength(1, DataGridLengthUnitType.Star);
            DataGridLength length1_5 = new DataGridLength(1.5, DataGridLengthUnitType.Star);
            DataGridLength length2   = new DataGridLength(2, DataGridLengthUnitType.Star);
            DataGridLength length2_5 = new DataGridLength(2.5, DataGridLengthUnitType.Star);
            DataGridLength length3   = new DataGridLength(3, DataGridLengthUnitType.Star);
            DataGridLength length4   = new DataGridLength(4, DataGridLengthUnitType.Star);

            //lastColumn.Width = length;
            dataGrid.Columns[0].Width  = length2;
            dataGrid.Columns[1].Width  = length3;
            dataGrid.Columns[2].Width  = length4;
            dataGrid.Columns[3].Width  = length1_5;
            dataGrid.Columns[4].Width  = length2;
            dataGrid.Columns[5].Width  = length1_5;
            dataGrid.Columns[6].Width  = length2;
            dataGrid.Columns[7].Width  = length2;
            dataGrid.Columns[8].Width  = length2;
            dataGrid.Columns[9].Width  = length1_5;
            dataGrid.Columns[10].Width = length2;

            Style styleCenter0 = new Style(typeof(DataGridColumnHeader));
            //Style styleRight0 = new Style(typeof(System.Windows.Controls.Datagrid));
            Style  styleCenter = new Style(typeof(TextBlock));
            Style  styleRight  = new Style(typeof(TextBlock));
            Setter setCenter   = new Setter(TextBlock.HorizontalAlignmentProperty, System.Windows.HorizontalAlignment.Center);
            Setter setRight    = new Setter(TextBlock.HorizontalAlignmentProperty, System.Windows.HorizontalAlignment.Right);
            //styleRight.Setters.Add(setRight);
            Setter setHead = new Setter(DataGridColumnHeader.HorizontalContentAlignmentProperty, System.Windows.HorizontalAlignment.Center);

            // Setter setHead1 = new Setter(DataGridColumnHeader., System.Windows.VerticalAlignment.Center);
            styleCenter.Setters.Add(setCenter);
            styleCenter0.Setters.Add(setHead);
            styleRight.Setters.Add(setRight);
            // styleRight0.Setters.Add(setHead1);
            foreach (DataGridColumn c in dataGrid.Columns)
            {
                DataGridTextColumn tc = c as DataGridTextColumn;
                if (tc.Header.ToString() != "总价" && tc.Header.ToString() != "单价")
                {
                    //tc.HeaderStyle = styleCenter0;
                    tc.ElementStyle = styleCenter;
                }
                else
                {
                    tc.ElementStyle = styleRight;
                }
                tc.HeaderStyle = styleCenter0;
            }
        }
Exemplo n.º 20
0
        // Exceptions:
        //   System.ArgumentNullException:
        //     value is null.
        //
        //   System.ArgumentException:
        //     value is not a valid type that can be converted to type System.Windows.Controls.DataGridLength.
        /// <summary>
        /// Converts the specified object to an instance of the System.Windows.Controls.DataGridLength
        /// class.
        /// </summary>
        /// <param name="context">An object that provides a format context.</param>
        /// <param name="culture">The object to use as the current culture.</param>
        /// <param name="value">The value to convert.</param>
        /// <returns>The converted value.</returns>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value == null)
            {
                throw GetConvertFromException(value);
            }

            if (value is string)
            {
                return(DataGridLength.INTERNAL_ConvertFromString((string)value));
            }

            return(base.ConvertFrom(context, culture, value));
        }
Exemplo n.º 21
0
        private void Button_Print_Click(object sender, RoutedEventArgs e)
        {
            var printDialog = new PrintDialog();

            if (printDialog.ShowDialog() != true)
            {
                return;
            }
            var myPanel = new StackPanel {
                Orientation = Orientation.Vertical, HorizontalAlignment = HorizontalAlignment.Stretch
            };

            myPanel.Children.Add(new TextBlock
            {
                Text          = "Статистика по ошибкам",
                TextAlignment = TextAlignment.Center,
                FontSize      = 16,
                FontWeight    = FontWeights.Bold,
                Margin        = new Thickness(0, 0, 0, 10)
            });
            myPanel.Children.Add(new TextBlock
            {
                Text = string.Format("Госномер: {0}, марка: {1}, модель автомобиля: {2}",
                                     _car.CarModel.CarNumber, _car.CarModel.Mark, _car.CarModel.Model),
                TextAlignment = TextAlignment.Center,
                FontSize      = 14,
                Margin        = new Thickness(0, 0, 0, 15)
            });

            var trr = new DataGrid {
                AutoGenerateColumns = false, HorizontalAlignment = HorizontalAlignment.Stretch
            };
            var wd = new DataGridLength(1, DataGridLengthUnitType.Star);

            trr.Columns.Add(new DataGridTextColumn {
                Header = "Номер ошибки", Binding = new Binding("ID"), Width = wd
            });
            trr.Columns.Add(new DataGridTextColumn {
                Header = "Кол-во", Binding = new Binding("Count"), Width = wd
            });
            trr.Columns.Add(new DataGridTextColumn {
                Header = "Зафикисирована", Binding = new Binding("LastDate"), Width = wd
            });
            trr.ItemsSource = dtgrdErrorsStat.ItemsSource;
            myPanel.Children.Add(trr);

            myPanel.Measure(new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight));
            //myPanel.Arrange(new Rect(new Point(0, 0), myPanel.DesiredSize));
            printDialog.PrintVisual(myPanel, "Статистика по ошибкам");
        }
Exemplo n.º 22
0
        public void DoubleToDataGridLengthConverterTest()
        {
            var            cvt = new DoubleToDataGridLengthConverter();
            double         v   = 1000000;
            DataGridLength l   = (DataGridLength)cvt.Convert(v, typeof(int), null, System.Globalization.CultureInfo.CurrentCulture);

            Assert.IsTrue(l.Value == v);

            v = 0;
            l = (DataGridLength)cvt.Convert(v, typeof(int), null, System.Globalization.CultureInfo.CurrentCulture);
            Assert.IsTrue(l.Value == v);

            v = -1;
            l = (DataGridLength)cvt.Convert(v, typeof(int), null, System.Globalization.CultureInfo.CurrentCulture);
            Assert.IsTrue(DataGridLength.Auto == l);
        }
Exemplo n.º 23
0
        /// <summary>
        ///
        /// </summary>
        public PropertyGrid()
        {
            Buttons = new FrameworkElementCollection();

            CommandBindings.Add(new CommandBinding(EditCollectionCommand, this.EditCollectionCommand_Executed, this.EditCollectionCommand_CanExecute));
            CommandBindings.Add(new CommandBinding(ResetCommand, this.ResetCommand_Executed, this.ResetCommand_CanExecute));

            Properties         = new PropertyModelCollection();
            ListCollectionView = new ListCollectionView(Properties);

            PropertyColumnWidth = new DataGridLength(40d, DataGridLengthUnitType.Star);
            ValueColumnWidth    = new DataGridLength(60d, DataGridLengthUnitType.Star);

            InitializeComponent();

            Sort();
        }
Exemplo n.º 24
0
        private void dataGrid1_AutoGeneratedColumns(object sender, EventArgs e)
        {
            var dg    = sender as DataGrid;
            var first = dg.ItemsSource.Cast <object>().FirstOrDefault() as DynamicObject;

            if (first == null)
            {
                return;
            }
            var            names = first.GetDynamicMemberNames();
            DataGridLength len   = new DataGridLength(1, DataGridLengthUnitType.Star);

            foreach (var name in names)
            {
                dg.Columns.Add(new DataGridTextColumn {
                    Header = name, Binding = new Binding(name), Width = len
                });
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Doubleの値をDataGridLengthに変換します。-1のときはDataGridLength.Autoに変換します。
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DataGridLength l = 0;

            if (value != null)
            {
                string d = value.ToString();
                switch (d)
                {
                case "-1":
                    l = DataGridLength.Auto;
                    break;

                default:
                    l = (double)value;
                    break;
                }
            }
            else
            {
                throw new ArgumentNullException("value");
            }
            return(l);
        }
Exemplo n.º 26
0
 public CustomBoundColumn()
 {
     Width = new DataGridLength(1, DataGridLengthUnitType.Star);
 }
 private void SetColumnsWidth(DataGridLength p_gridLengthNewValue)
 {
     foreach (var objCol in dgvVisualizer.Columns)
     {
         objCol.Width = p_gridLengthNewValue;
     }
 }
Exemplo n.º 28
0
 public GenerateOperatorGridColumn()
 {
     Width = new DataGridLength(1, DataGridLengthUnitType.Star);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Measures the children of a <see cref="T:System.Windows.Controls.Primitives.DataGridCellsPresenter"/> to
        /// prepare for arranging them during the <see cref="M:System.Windows.FrameworkElement.ArrangeOverride(System.Windows.Size)"/> pass.
        /// </summary>
        /// <param name="availableSize">
        /// The available size that this element can give to child elements. Indicates an upper limit that child elements should not exceed.
        /// </param>
        /// <returns>
        /// The size that the <see cref="T:System.Windows.Controls.Primitives.DataGridCellsPresenter"/> determines it needs during layout, based on its calculations of child object allocated sizes.
        /// </returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            if (this.OwningGrid == null)
            {
                return(base.MeasureOverride(availableSize));
            }

            bool   autoSizeHeight;
            double measureHeight;

            if (double.IsNaN(this.OwningGrid.RowHeight))
            {
                // No explicit height values were set so we can autosize
                autoSizeHeight = true;
                measureHeight  = double.PositiveInfinity;
            }
            else
            {
                this.DesiredHeight = this.OwningGrid.RowHeight;
                measureHeight      = this.DesiredHeight;
                autoSizeHeight     = false;
            }

            double frozenLeftEdge    = 0;
            double totalDisplayWidth = 0;
            double scrollingLeftEdge = -this.OwningGrid.HorizontalOffset;

            this.OwningGrid.ColumnsInternal.EnsureVisibleEdgedColumnsWidth();
            DataGridColumn lastVisibleColumn = this.OwningGrid.ColumnsInternal.LastVisibleColumn;

            foreach (DataGridColumn column in this.OwningGrid.ColumnsInternal.GetVisibleColumns())
            {
                DataGridCell cell = this.OwningRow.Cells[column.Index];

                // Measure the entire first row to make the horizontal scrollbar more accurate
                bool shouldDisplayCell = ShouldDisplayCell(column, frozenLeftEdge, scrollingLeftEdge) || this.OwningRow.Index == 0;
                EnsureCellDisplay(cell, shouldDisplayCell);
                if (shouldDisplayCell)
                {
                    DataGridLength columnWidth   = column.Width;
                    bool           autoGrowWidth = columnWidth.IsSizeToCells || columnWidth.IsAuto;
                    if (column != lastVisibleColumn)
                    {
                        cell.EnsureGridLine(lastVisibleColumn);
                    }

                    // If we're not using star sizing or the current column can't be resized,
                    // then just set the display width according to the column's desired width
                    if (!this.OwningGrid.UsesStarSizing || (!column.ActualCanUserResize && !column.Width.IsStar))
                    {
                        // In the edge-case where we're given infinite width and we have star columns, the
                        // star columns grow to their predefined limit of 10,000 (or their MaxWidth)
                        double newDisplayWidth = column.Width.IsStar ?
                                                 Math.Min(column.ActualMaxWidth, DataGrid.DATAGRID_maximumStarColumnWidth) :
                                                 Math.Max(column.ActualMinWidth, Math.Min(column.ActualMaxWidth, column.Width.DesiredValue));
                        column.SetWidthDisplayValue(newDisplayWidth);
                    }

                    // If we're auto-growing the column based on the cell content, we want to measure it at its maximum value
                    if (autoGrowWidth)
                    {
                        cell.Measure(new Size(column.ActualMaxWidth, measureHeight));
                        this.OwningGrid.AutoSizeColumn(column, cell.DesiredSize.Width);
                        column.ComputeLayoutRoundedWidth(totalDisplayWidth);
                    }
                    else if (!this.OwningGrid.UsesStarSizing)
                    {
                        column.ComputeLayoutRoundedWidth(scrollingLeftEdge);
                        cell.Measure(new Size(column.LayoutRoundedWidth, measureHeight));
                    }

                    // We need to track the largest height in order to auto-size
                    if (autoSizeHeight)
                    {
                        this.DesiredHeight = Math.Max(this.DesiredHeight, cell.DesiredSize.Height);
                    }
                }

                if (column.IsFrozen)
                {
                    frozenLeftEdge += column.ActualWidth;
                }

                scrollingLeftEdge += column.ActualWidth;
                totalDisplayWidth += column.ActualWidth;
            }

            // If we're using star sizing (and we're not waiting for an auto-column to finish growing)
            // then we will resize all the columns to fit the available space.
            if (this.OwningGrid.UsesStarSizing && !this.OwningGrid.AutoSizingColumns)
            {
                double adjustment = this.OwningGrid.CellsWidth - totalDisplayWidth;
                this.OwningGrid.AdjustColumnWidths(0, adjustment, false);

                // Since we didn't know the final widths of the columns until we resized,
                // we waited until now to measure each cell
                double leftEdge = 0;
                foreach (DataGridColumn column in this.OwningGrid.ColumnsInternal.GetVisibleColumns())
                {
                    DataGridCell cell = this.OwningRow.Cells[column.Index];
                    column.ComputeLayoutRoundedWidth(leftEdge);
                    cell.Measure(new Size(column.LayoutRoundedWidth, measureHeight));
                    if (autoSizeHeight)
                    {
                        this.DesiredHeight = Math.Max(this.DesiredHeight, cell.DesiredSize.Height);
                    }

                    leftEdge += column.ActualWidth;
                }
            }

            // Measure FillerCell, we're doing it unconditionally here because we don't know if we'll need the filler
            // column and we don't want to cause another Measure if we do
            this.OwningRow.FillerCell.Measure(new Size(double.PositiveInfinity, this.DesiredHeight));

            this.OwningGrid.ColumnsInternal.EnsureVisibleEdgedColumnsWidth();
            return(new Size(this.OwningGrid.ColumnsInternal.VisibleEdgedColumnsWidth, this.DesiredHeight));
        }
 /// <summary>
 /// Sets the width of the set last column.
 /// </summary>
 /// <param name="obj">The obj.</param>
 /// <param name="value">The value.</param>
 public static void SetSetLastColumnWidth(DependencyObject obj, DataGridLength value)
 {
     obj.SetValue(SetLastColumnWidthProperty, value);
 }
Exemplo n.º 31
0
		static public void ColumnResize(this DataGrid dg, string sName, DataGridLength stDGL)
		{
			DataGridColumn dgcColumn;
			if (null != (dgcColumn = dg.ColumnGet(sName)))
				dgcColumn.Width = stDGL;
		}
        /// <summary>
        /// Coerces a DataGridLength to a valid value.  If any value components are double.NaN, this method
        /// coerces them to a proper initial value.  For star columns, the desired width is calculated based
        /// on the rest of the star columns.  For pixel widths, the desired value is based on the pixel value.
        /// For auto widths, the desired value is initialized as the column's minimum width.
        /// </summary>
        /// <param name="width">The DataGridLength to coerce.</param>
        /// <returns>The resultant (coerced) DataGridLength.</returns>
        internal DataGridLength CoerceWidth(DataGridLength width)
        {
            double desiredValue = width.DesiredValue;
            if (double.IsNaN(desiredValue))
            {
                if (width.IsStar && this.OwningGrid != null && this.OwningGrid.ColumnsInternal != null)
                {
                    double totalStarValues = 0;
                    double totalStarDesiredValues = 0;
                    double totalNonStarDisplayWidths = 0;
                    foreach (DataGridColumn column in this.OwningGrid.ColumnsInternal.GetDisplayedColumns(c => c.IsVisible && c != this && !double.IsNaN(c.Width.DesiredValue)))
                    {
                        if (column.Width.IsStar)
                        {
                            totalStarValues += column.Width.Value;
                            totalStarDesiredValues += column.Width.DesiredValue;
                        }
                        else
                        {
                            totalNonStarDisplayWidths += column.ActualWidth;
                        }
                    }
                    if (totalStarValues == 0)
                    {
                        // Compute the new star column's desired value based on the available space if there are no other visible star columns
                        desiredValue = Math.Max(this.ActualMinWidth, this.OwningGrid.CellsWidth - totalNonStarDisplayWidths);
                    }
                    else
                    {
                        // Otherwise, compute its desired value based on those of other visible star columns
                        desiredValue = totalStarDesiredValues * width.Value / totalStarValues;
                    }
                }
                else if (width.IsAbsolute)
                {
                    desiredValue = width.Value;
                }
                else
                {
                    desiredValue = this.ActualMinWidth;
                }
            }

            double displayValue = width.DisplayValue;
            if (double.IsNaN(displayValue))
            {
                displayValue = desiredValue;
            }
            displayValue = Math.Max(this.ActualMinWidth, Math.Min(this.ActualMaxWidth, displayValue));

            return new DataGridLength(width.Value, width.UnitType, desiredValue, displayValue);
        }
 /// <summary>
 /// Sets the column's Width directly, without any callback effects.
 /// </summary>
 /// <param name="width">The new Width.</param>
 internal void SetWidthInternalNoCallback(DataGridLength width)
 {
     _width = width;
 }
Exemplo n.º 34
0
        /// <summary>
        ///     Converts a DataGridLength instance to a String given the CultureInfo.
        /// </summary>
        /// <param name="gl">DataGridLength instance to convert.</param>
        /// <param name="cultureInfo">The culture to use.</param>
        /// <returns>String representation of the object.</returns>
        internal static string ConvertToString(DataGridLength length, CultureInfo cultureInfo)
        {
            switch (length.UnitType)
            {
                case DataGridLengthUnitType.Auto:
                case DataGridLengthUnitType.SizeToCells:
                case DataGridLengthUnitType.SizeToHeader:
                    return length.UnitType.ToString();

                // Star has one special case when value is "1.0" in which the value can be dropped.
                case DataGridLengthUnitType.Star:
                    return DoubleUtil.IsOne(length.Value) ? "*" : Convert.ToString(length.Value, cultureInfo) + "*";

                // Print out the numeric value. "px" can be omitted.
                default:
                    return Convert.ToString(length.Value, cultureInfo);
            }
        }
Exemplo n.º 35
0
 /// <summary>
 /// Internal method which sets the column's width
 /// without actual redistribution of widths among other
 /// columns
 /// </summary>
 /// <param name="width"></param>
 internal void SetWidthInternal(DataGridLength width)
 {
     bool originalValue = _ignoreRedistributionOnWidthChange;
     _ignoreRedistributionOnWidthChange = true;
     try
     {
         Width = width;
     }
     finally
     {
         _ignoreRedistributionOnWidthChange = originalValue;
     }
 }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DataGridLength length = (DataGridLength)value;

            return(length.DisplayValue);
        }
Exemplo n.º 37
0
        protected override Size MeasureOverride(Size availableSize)
        {
            if (this.OwningGrid == null)
            {
                return(base.MeasureOverride(availableSize));
            }
            if (!this.OwningGrid.AreColumnHeadersVisible)
            {
                return(Size.Empty);
            }
            double height = this.OwningGrid.ColumnHeaderHeight;
            bool   autoSizeHeight;

            if (double.IsNaN(height))
            {
                // No explicit height values were set so we can autosize
                height         = 0;
                autoSizeHeight = true;
            }
            else
            {
                autoSizeHeight = false;
            }

            DataGridColumn lastVisibleColumn = this.OwningGrid.ColumnsInternal.LastVisibleColumn;
            DataGridColumn column            = this.OwningGrid.ColumnsInternal.FirstVisibleColumn;
            double         measureWidth;

            while (column != null)
            {
                DataGridLength columnWidth = column.EffectiveWidth;
                measureWidth = columnWidth.IsAbsolute ? column.ActualWidth : column.ActualMaxWidth;
                bool autoGrowWidth = columnWidth.IsAuto || columnWidth.IsSizeToHeader;

                DataGridColumnHeader columnHeader = column.HeaderCell;
                if (column != lastVisibleColumn)
                {
                    columnHeader.UpdateSeparatorVisibility(lastVisibleColumn);
                }
                columnHeader.Measure(new Size(measureWidth, double.PositiveInfinity));
                if (autoSizeHeight)
                {
                    height = Math.Max(height, columnHeader.DesiredSize.Height);
                }
                if (autoGrowWidth && columnHeader.DesiredSize.Width > column.DesiredWidth)
                {
                    column.DesiredWidth = columnHeader.DesiredSize.Width;
                }

                column = this.OwningGrid.ColumnsInternal.GetNextVisibleColumn(column);
            }

            // Add the filler column if it's not represented.  We won't know whether we need it or not until Arrange
            DataGridFillerColumn fillerColumn = this.OwningGrid.ColumnsInternal.FillerColumn;

            if (!fillerColumn.IsRepresented)
            {
                Debug.Assert(!this.Children.Contains(fillerColumn.HeaderCell));
                fillerColumn.HeaderCell.SeparatorVisibility = Visibility.Collapsed;
                this.Children.Insert(this.OwningGrid.ColumnsInternal.Count, fillerColumn.HeaderCell);
                fillerColumn.IsRepresented = true;
                this.OwningGrid.OnFillerColumnRepresentationChanged();
                // Optimize for the case where we don't need the filler cell
                fillerColumn.HeaderCell.Visibility = Visibility.Collapsed;
            }
            fillerColumn.HeaderCell.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

            return(new Size(this.OwningGrid.ColumnsInternal.VisibleEdgedColumnsWidth, height));
        }
 /// <summary>
 /// Set the column's Width without breaking inheritance.
 /// </summary>
 /// <param name="width">The new Width.</param>
 internal void SetWidthInternal(DataGridLength width)
 {
     bool originalValue = _settingWidthInternally;
     _settingWidthInternally = true;
     try
     {
         this.Width = width;
     }
     finally
     {
         _settingWidthInternally = originalValue;
     }
 }