public ColumnConfigurator(FastGrid grid)
 {
     InitializeComponent();
     this.grid = grid;
     foreach (var column in grid.Columns)
         if (column.Visible)
             listBoxVisible.Items.Add(column.Title);
         else
             listBoxAvailable.Items.Add(column.Title);
 }
示例#2
0
 public FastGridTyped(FastGrid grid)
 {
     this.grid         = grid;
     grid.UserHitCell += (sender, args, index, col) =>
     {
         if (userHitCell != null)
         {
             userHitCell(sender, args, index, col, (T)grid.rows[index].ValueObject);
         }
     };
 }
示例#3
0
        public FastRow(FastGrid owner, object obj, Dictionary <FastColumn, PropertyInfo> columnProperty)
        {
            this.owner  = owner;
            ValueObject = obj;
            if (owner.colorFormatter != null)
            {
                Color?clBack, clFont;
                owner.colorFormatter(ValueObject, out clBack, out clFont);
                BackgroundColor = clBack;
                FontColor       = clFont;
            }

            string[] strings = null;
            if (owner.rowExtraFormatter != null)
            {
                strings = owner.rowExtraFormatter(obj, columnProperty.Select(propertyInfo => propertyInfo.Key).ToList());
            }

            var counter = 0;

            foreach (var colPair in columnProperty)
            {
                var cell = new FastCell();
                if (colPair.Value == null)
                {
                    cells.Add(cell);
                    continue;
                }
                // do format value
                var proVal = colPair.Value.GetValue(obj, null);
                cell.CellValue  = proVal;
                cell.CellString = strings == null ?
                                  (colPair.Key.formatter != null ? colPair.Key.formatter(proVal)
                    : colPair.Key.rowFormatter != null ? colPair.Key.rowFormatter(obj)
                    : proVal == null
                    ? colPair.Key.NullString
                    : ObjectToString(proVal, colPair.Key.FormatString, colPair.Key.FractionDigits)) : strings[counter++];
                if (colPair.Key.cellFormatting != null)
                {
                    var args = new CellFormattingEventArgs
                    {
                        cellValue      = cell.CellValue,
                        resultedString = cell.CellString,
                        column         = colPair.Key,
                        rowValue       = obj,
                    };
                    colPair.Key.cellFormatting(args);
                    cell.CellString = args.resultedString;
                }
                cells.Add(cell);
            }
        }
示例#4
0
        public FastRow(FastGrid owner, object obj, Dictionary<FastColumn, PropertyInfo> columnProperty)
        {
            this.owner = owner;
            ValueObject = obj;
            if (owner.colorFormatter != null)
            {
                Color? clBack, clFont;
                owner.colorFormatter(ValueObject, out clBack, out clFont);
                BackgroundColor = clBack;
                FontColor = clFont;
            }

            string[] strings = null;
            if (owner.rowExtraFormatter != null)
                strings = owner.rowExtraFormatter(obj, columnProperty.Select(propertyInfo => propertyInfo.Key).ToList());

            var counter = 0;
            foreach (var colPair in columnProperty)
            {
                var cell = new FastCell();
                if (colPair.Value == null)
                {
                    cells.Add(cell);
                    continue;
                }
                // do format value
                var proVal = colPair.Value.GetValue(obj, null);
                cell.CellValue = proVal;
                cell.CellString = strings == null ?
                    (colPair.Key.formatter != null ? colPair.Key.formatter(proVal)
                    : colPair.Key.rowFormatter != null ? colPair.Key.rowFormatter(obj)
                    : proVal == null
                    ? colPair.Key.NullString
                    : ObjectToString(proVal, colPair.Key.FormatString, colPair.Key.FractionDigits)) : strings[counter++];
                if (colPair.Key.cellFormatting != null)
                {
                    var args = new CellFormattingEventArgs
                        {
                            cellValue = cell.CellValue,
                            resultedString = cell.CellString,
                            column = colPair.Key,
                            rowValue = obj,
                        };
                    colPair.Key.cellFormatting(args);
                    cell.CellString = args.resultedString;
                }
                cells.Add(cell);
            }
        }
示例#5
0
        public GridDropDialog(int left, int top, int width, int height,
                              int minTableWidth, int fixedTableWidth,
                              Color cellBackColor, Color altBackColor, Color fontColor,
                              IEnumerable <FastColumn> columns, IList boundObjects, object selectedObj)
        {
            InitializeComponent();
            grid = new FastGrid {
                Dock = DockStyle.Fill, Parent = this
            };
            Controls.Add(grid);

            Text            = string.Empty;
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MinimizeBox     = false;
            MaximizeBox     = false;
            ControlBox      = false;
            ShowInTaskbar   = false;
            TopMost         = true;
            Capture         = true;

            grid.Columns.AddRange(columns);
            if (minTableWidth > 0)
            {
                grid.MinimumTableWidth = minTableWidth;
            }
            if (fixedTableWidth > 0)
            {
                width = fixedTableWidth;
            }
            grid.ColorAltCellBackground = altBackColor;
            grid.ColorCellBackground    = cellBackColor;
            grid.ColorCellFont          = fontColor;
            grid.DataBind(boundObjects);
            if (selectedObj != null)
            {
                foreach (var row in grid.rows)
                {
                    if (row.ValueObject == selectedObj)
                    {
                        row.Selected = true;
                        break;
                    }
                }
            }
            grid.UserHitCell += GridUserHitCell;

            SetBounds(left, top, width, height);
        }
 public ColumnConfigurator(FastGrid grid)
 {
     InitializeComponent();
     this.grid = grid;
     foreach (var column in grid.Columns)
     {
         if (column.Visible)
         {
             listBoxVisible.Items.Add(column.Title);
         }
         else
         {
             listBoxAvailable.Items.Add(column.Title);
         }
     }
 }
示例#7
0
        public GridDropDialog(int left, int top, int width, int height,
            int minTableWidth, int fixedTableWidth,
            Color cellBackColor, Color altBackColor, Color fontColor,
            IEnumerable<FastColumn> columns, IList boundObjects, object selectedObj)
        {
            InitializeComponent();
            grid = new FastGrid {Dock = DockStyle.Fill, Parent = this};
            Controls.Add(grid);

            Text = string.Empty;
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MinimizeBox = false;
            MaximizeBox = false;
            ControlBox = false;
            ShowInTaskbar = false;
            TopMost = true;
            Capture = true;

            grid.Columns.AddRange(columns);
            if (minTableWidth > 0) grid.MinimumTableWidth = minTableWidth;
            if (fixedTableWidth > 0) width = fixedTableWidth;
            grid.ColorAltCellBackground = altBackColor;
            grid.ColorCellBackground = cellBackColor;
            grid.ColorCellFont = fontColor;
            grid.DataBind(boundObjects);
            if (selectedObj != null)
            {
                foreach (var row in grid.rows)
                {
                    if (row.ValueObject == selectedObj)
                    {
                        row.Selected = true;
                        break;
                    }
                }
            }
            grid.UserHitCell += GridUserHitCell;

            SetBounds(left, top, width, height);
        }
示例#8
0
 private void SetupPaymentGrid(FastGrid.FastGrid grid)
 {
     var blank = new Transfer();
     // платежи
     grid.Columns.Add(new FastColumn(blank.Property(p => p.Id), "#") { SortOrder = FastColumnSort.Ascending, ColumnWidth = 60 });
     grid.Columns.Add(new FastColumn(blank.Property(p => p.ValueDate), Localizer.GetString("TitleTime"))
     {
         ColumnMinWidth = 75,
         rowFormatter = valueObject =>
         {
             var transfer = (Transfer)valueObject;
             return transfer.Id == 0 ? "" : transfer.ValueDate.ToStringUniform();
         }
     });
     grid.Columns.Add(new FastColumn(blank.Property(p => p.TargetAmount), Localizer.GetString("TitleSum"))
     {
         ColumnMinWidth = 75,
         rowFormatter = valueObject =>
         {
             var transfer = (Transfer) valueObject;
             return transfer.Id == 0 ? "" :
                 transfer.TargetAmount.ToStringUniformMoneyFormat() + " " + walletCurrency;
         }
     });
     grid.Columns.Add(new FastColumn(blank.Property(p => p.Comment), Localizer.GetString("TitleComment"))
     {
         ColumnMinWidth = 75,
         rowFormatter = valueObject =>
         {
             var transfer = (Transfer) valueObject;
             if (transfer.Subscription.HasValue)
             {
                 return Localizer.GetString("TitleServiceSubscription");
             }
             if (transfer.RefWallet.HasValue)
             {
                 return Localizer.GetString("TitleWalletPayment") + " #" + transfer.RefWallet.Value;
             }
             if (transfer.BalanceChange.HasValue)
             {
                 return Localizer.GetString("TitleTransferToTradeAccount");
             }
             return transfer.Comment;
         },
         IsHyperlinkStyleColumn = true,
         HyperlinkActiveCursor = Cursors.Hand,
         ColorHyperlinkTextActive = Color.Blue,
         HyperlinkFontActive = new Font(Font, FontStyle.Bold)
     });
     grid.colorFormatter = (object value, out Color? color, out Color? fontColor) =>
     {
         color = null;
         fontColor = null;
         var trans = value as Transfer;
         if (trans == null)
             return;
         if (trans.Id == 0)
             color = Color.Lime;
     };
     grid.UserHitCell += GridPaymentOnUserHitCell;
     grid.CalcSetTableMinWidth();
 }
示例#9
0
        private void Rebuild()
        {
            // ищем отображаемые свойства как пересечение множеств свойств выбранных объектов
            var selectedProperties = new List<PropertyInfo>();
            if (selectedObjects != null)
            {
                var chartObjectPropertiesDict = new Dictionary<object, List<PropertyInfo>>();
                var allProperties = new List<PropertyInfo>();
                foreach (var chartObject in selectedObjects)
                {
                    var chartObjectProperties = chartObject.GetType().GetProperties().Where(IsBrowsable).ToList();
                    chartObjectPropertiesDict.Add(chartObject, chartObjectProperties);
                    allProperties.AddRange(chartObjectProperties);
                }
                // ищем пересечение
                foreach (var property in allProperties)
                {
                    var add = true;
                    foreach (var chartObject in selectedObjects)
                    {
                        // одинаковые по сути свойства представлены разными объектами PropertyInfo,
                        // а IEquatable.Equals сравнивает ссылки, поэтому проверку на равенство выполняем самостоятельно
                        if (!chartObjectPropertiesDict[chartObject].Any(p => p.Name == property.Name && p.PropertyType == property.PropertyType))
                        {
                            add = false;
                            break;
                        }
                    }
                    if (add && !selectedProperties.Any(p => p.Name == property.Name && p.PropertyType == property.PropertyType))
                        selectedProperties.Add(property);
                }
            }
            else if (selectedObject != null)
                selectedProperties = selectedObject.GetType().GetProperties().Where(IsBrowsable).ToList();

            // определяем категории
            var categories = new List<Cortege2<string, int>>();
            foreach (var property in selectedProperties)
            {
                var category = GetCategory(property);
                if (!string.IsNullOrEmpty(category) && !categories.Exists(c => c.a == category))
                    categories.Add(new Cortege2<string, int>(category, GetOrder(property).b));
            }

            // сортируем категории
            categories.Sort((arg1, arg2) => arg1.b - arg2.b);

            // для каждой категории создаем по вкладке
            tabControl.TabPages.Clear();
            var blankRow = new FastPropertyGridRow();
            foreach (var category in categories)
            {
                tabControl.TabPages.Add(category.a, category.a);
                var fastGrid = new FastGrid.FastGrid {Dock = DockStyle.Fill, FitWidth = true, CaptionHeight = 0};
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.Title)));
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.StringValue)) {ColumnFont = new Font(Font, FontStyle.Bold)});
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.Property)) {Visible = false});
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.Value)) {Visible = false});
                fastGrid.UserHitCell += UserHitCell;
                tabControl.TabPages[category.a].Controls.Add(fastGrid);
                // определяем свойства внутри категории
                var propertiesInCategory = new List<Cortege2<PropertyInfo, int>>();
                foreach (var property in selectedProperties)
                {
                    if (GetCategory(property) != category.a)
                        continue;
                    propertiesInCategory.Add(new Cortege2<PropertyInfo, int>(property, GetOrder(property).a));
                }

                // сортируем свойства
                propertiesInCategory.Sort((arg1, arg2) => arg1.b - arg2.b);

                // создаем данные типа "имя-значение"
                var data = new List<FastPropertyGridRow>();
                foreach (var property in propertiesInCategory)
                {
                    // в случае множества объектов, null - фиктивное значение (значение, используемое для отображения в случае различных значений)
                    object value = null;
                    if (selectedObjects != null)
                    {
                        var allValues = GetDistinctPropertyValues(selectedObjects, property.a);
                        if (allValues.Count == 1)
                            value = allValues.First();
                    }
                    else if (selectedObject != null)
                        value = property.a.GetValue(selectedObject, null);

                    data.Add(new FastPropertyGridRow
                        {
                            Title = GetDisplayName(property.a),
                            Value = value,
                            Property = property.a,
                            StringValue = GetStringValue(value, property.a)
                        });
                }
                fastGrid.DataBind(data);

                // фиксируем ширину колонки с наименованием
                fastGrid.CheckSize(true);
            }
            RebuildSample();
        }
示例#10
0
 // открытие стандартного редактора в зависимости от типа свойства
 private void OpenBaseEditor(PropertyInfo property, FastGrid.FastGrid fastGrid, int rowIndex, FastColumn col)
 {
     var coords = fastGrid.GetCellCoords(col, rowIndex);
     var blankRow = new FastPropertyGridRow();
     var cellValue =
         fastGrid.rows[rowIndex].cells[fastGrid.Columns.FindIndex(c => c.PropertyName == blankRow.Property(p => p.Value))].CellValue;
     var propType = property.PropertyType;
     if ((propType == typeof (bool) || propType.IsEnum))
     {
         var pop = new PopupListBox(cellValue, rowIndex, col, propType, UpdateObject, fastGrid);
         pop.ShowOptions(coords.X, coords.Y);
         return;
     }
     if ((propType == typeof (string) || Converter.IsConvertable(propType)))
     {
         // редактор подставляется в FastGrid.PopupTextBox
         try
         {
             var pop = new PopupTextBox(cellValue, col.ResultedWidth, fastGrid.CellHeight, rowIndex, col, property, null);
             pop.OnValueUpdated += UpdateObject;
             pop.Show(fastGrid, coords);
         }
         catch(Exception ex)
         {
             Logger.Error("FastPropertyGrid.OpenBaseEditor", ex);
         }
         return;
     }
 }
示例#11
0
        private void Rebuild()
        {
            // ищем отображаемые свойства как пересечение множеств свойств выбранных объектов
            var selectedProperties = new List <PropertyInfo>();

            if (selectedObjects != null)
            {
                var chartObjectPropertiesDict = new Dictionary <object, List <PropertyInfo> >();
                var allProperties             = new List <PropertyInfo>();
                foreach (var chartObject in selectedObjects)
                {
                    var chartObjectProperties = chartObject.GetType().GetProperties().Where(IsBrowsable).ToList();
                    chartObjectPropertiesDict.Add(chartObject, chartObjectProperties);
                    allProperties.AddRange(chartObjectProperties);
                }
                // ищем пересечение
                foreach (var property in allProperties)
                {
                    var add = true;
                    foreach (var chartObject in selectedObjects)
                    {
                        // одинаковые по сути свойства представлены разными объектами PropertyInfo,
                        // а IEquatable.Equals сравнивает ссылки, поэтому проверку на равенство выполняем самостоятельно
                        if (!chartObjectPropertiesDict[chartObject].Any(p => p.Name == property.Name && p.PropertyType == property.PropertyType))
                        {
                            add = false;
                            break;
                        }
                    }
                    if (add && !selectedProperties.Any(p => p.Name == property.Name && p.PropertyType == property.PropertyType))
                    {
                        selectedProperties.Add(property);
                    }
                }
            }
            else if (selectedObject != null)
            {
                selectedProperties = selectedObject.GetType().GetProperties().Where(IsBrowsable).ToList();
            }

            // определяем категории
            var categories = new List <Cortege2 <string, int> >();

            foreach (var property in selectedProperties)
            {
                var category = GetCategory(property);
                if (!string.IsNullOrEmpty(category) && !categories.Exists(c => c.a == category))
                {
                    categories.Add(new Cortege2 <string, int>(category, GetOrder(property).b));
                }
            }

            // сортируем категории
            categories.Sort((arg1, arg2) => arg1.b - arg2.b);

            // для каждой категории создаем по вкладке
            tabControl.TabPages.Clear();
            var blankRow = new FastPropertyGridRow();

            foreach (var category in categories)
            {
                tabControl.TabPages.Add(category.a, category.a);
                var fastGrid = new FastGrid.FastGrid {
                    Dock = DockStyle.Fill, FitWidth = true, CaptionHeight = 0
                };
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.Title)));
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.StringValue))
                {
                    ColumnFont = new Font(Font, FontStyle.Bold)
                });
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.Property))
                {
                    Visible = false
                });
                fastGrid.Columns.Add(new FastColumn(blankRow.Property(p => p.Value))
                {
                    Visible = false
                });
                fastGrid.UserHitCell += UserHitCell;
                tabControl.TabPages[category.a].Controls.Add(fastGrid);
                // определяем свойства внутри категории
                var propertiesInCategory = new List <Cortege2 <PropertyInfo, int> >();
                foreach (var property in selectedProperties)
                {
                    if (GetCategory(property) != category.a)
                    {
                        continue;
                    }
                    propertiesInCategory.Add(new Cortege2 <PropertyInfo, int>(property, GetOrder(property).a));
                }

                // сортируем свойства
                propertiesInCategory.Sort((arg1, arg2) => arg1.b - arg2.b);

                // создаем данные типа "имя-значение"
                var data = new List <FastPropertyGridRow>();
                foreach (var property in propertiesInCategory)
                {
                    // в случае множества объектов, null - фиктивное значение (значение, используемое для отображения в случае различных значений)
                    object value = null;
                    if (selectedObjects != null)
                    {
                        var allValues = GetDistinctPropertyValues(selectedObjects, property.a);
                        if (allValues.Count == 1)
                        {
                            value = allValues.First();
                        }
                    }
                    else if (selectedObject != null)
                    {
                        value = property.a.GetValue(selectedObject, null);
                    }

                    data.Add(new FastPropertyGridRow
                    {
                        Title       = GetDisplayName(property.a),
                        Value       = value,
                        Property    = property.a,
                        StringValue = GetStringValue(value, property.a)
                    });
                }
                fastGrid.DataBind(data);

                // фиксируем ширину колонки с наименованием
                fastGrid.CheckSize(true);
            }
            RebuildSample();
        }
示例#12
0
 private void ConfigFastGridColumns(FastGrid.FastGrid grid, string gridCode)
 {
     var columnConfigurator = new ColumnConfigurator(grid);
     if (columnConfigurator.ShowDialog(this) == DialogResult.Cancel)
         return;
     var sets = GridSettings.EnsureSettings(gridCode);
     sets.DeriveFromGrid(grid);
 }
示例#13
0
 private void ConfigHistoryGridColumns(FastGrid.FastGrid grid)
 {
     ConfigFastGridColumns(grid, GridSettings.ListAccountClosedOrders);
 }
示例#14
0
        // отобразить данные суммарной статистики
        public static void BindSummaryStatistics(FastGrid.FastGrid gridSummaryStat, PerformerStat performerStat, AccountEfficiency efficiency, bool showFullInfo)
        {
            if (performerStat == null)
                return;

            // суммарная статистика
            var rowColors = new[] { Color.Red, Color.Blue, Color.Black };
            var color = performerStat.Profit >= 0 ? rowColors[1] : rowColors[0];
            var statItems = new List<SummaryStatItem>();
            if (showFullInfo)
            {
                statItems.Add(
                    new SummaryStatItem(
                        string.Format("{0}\t{1}", Localizer.GetString("TitleSubscriberCount"),
                                      performerStat.SubscriberCount),
                        rowColors[2]));
                statItems.Add(
                    new SummaryStatItem(string.Format("{0}\t{1}", Localizer.GetString("TitleInvestorCount"), 0),
                                        rowColors[2]));
                statItems.Add(new SummaryStatItem(
                                  string.Format("{0}, {1}\t{2}", Localizer.GetString("TitleFundsUnderManagementShort"),
                                                performerStat.DepoCurrency,
                                                performerStat.Equity.ToStringUniformMoneyFormat()), rowColors[2]));
            }
            statItems.Add(new SummaryStatItem(Localizer.GetString("TitleTotalProfit"), rowColors[2]));
            statItems.Add(new SummaryStatItem(string.Format("{0} {1} / {2:f2}% / {3} {4}",
                                                            performerStat.ProfitLastMonthsAbs.ToStringUniformMoneyFormat(false),
                                                            performerStat.DepoCurrency,
                                                            performerStat.Profit,
                                                            performerStat.SumProfitPoints.ToStringUniformMoneyFormat(false),
                                                            Localizer.GetString("TitlePointsUnits")), color));

            if (efficiency != null && efficiency.openedDeals != null && efficiency.openedDeals.Count > 0)
            {
                var openResultDepo = efficiency.openedDeals.Sum(o => o.ResultDepo);
                var openResultPoints = efficiency.openedDeals.Sum(o => o.ResultPoints);
                var openResultPercent = performerStat.Equity == 0 ? 0
                                            : 100 * openResultDepo / performerStat.Equity;
                var colorOpen = openResultDepo >= 0 ? rowColors[1] : rowColors[0];
                statItems.Add(new SummaryStatItem(Localizer.GetString("TitleCurrentProfit"), rowColors[2]));
                statItems.Add(new SummaryStatItem(string.Format("{0} {1} / {2:f2}% / {3} {4}",
                                                      openResultDepo.ToStringUniformMoneyFormat(),
                                                      performerStat.DepoCurrency,
                                                      openResultPercent,
                                                      openResultPoints.ToStringUniformMoneyFormat(),
                                                      Localizer.GetString("TitlePointsUnits")),
                                        colorOpen));
            }

            gridSummaryStat.DataBind(statItems);
        }
示例#15
0
        public void ApplyToGrid(FastGrid.FastGrid grid)
        {
            var titles  = Titles;
            var columns = new List <FastColumn>();

            // видимость колонок
            foreach (var column in grid.Columns)
            {
                if (!titles.Contains(column.PropertyName))
                {
                    column.Visible = false;
                }
                columns.Add(column);
            }
            // порядок колонок
            for (var titleIndex = titles.Count - 1; titleIndex >= 0; titleIndex--)
            {
                var columnIndex = columns.FindIndex(c => c.PropertyName == titles[titleIndex]);
                if (columnIndex == -1)
                {
                    continue;
                }
                var column = columns[columnIndex];
                columns.RemoveAt(columnIndex);
                columns.Insert(0, column);
            }
            // проверка на правильность настроек
            var allCorrect = titles.All(title => grid.Columns.Any(c => c.PropertyName == title));

            if (allCorrect && columns.Any(c => c.Visible)) // не допускать невидимости всех колонок
            {
                grid.Columns = columns;
            }
            else
            {
                grid.Columns.ForEach(c => c.Visible = true);
            }
            // сортировка записей по отдельным колонкам
            var orders = SortOrders;

            if (orders != null)
            {
                for (var i = 0; i < orders.Count; i++)
                {
                    if (i >= grid.Columns.Count)
                    {
                        break;
                    }
                    grid.Columns[i].SortOrder = orders[i];
                }
            }
            // установка относительной ширины
            var relativeColumnsWidth = RelativeColumnsWidth;

            if (relativeColumnsWidth != null)
            {
                for (var i = 0; i < relativeColumnsWidth.Count; i++)
                {
                    if (i >= grid.Columns.Count)
                    {
                        break;
                    }
                    grid.Columns[i].RelativeWidth = relativeColumnsWidth[i];
                }
            }
        }
示例#16
0
 public void DeriveFromGrid(FastGrid.FastGrid grid)
 {
     var visibleColumns = grid.Columns.Where(c => c.Visible).ToList();
     Titles = visibleColumns.Select(c => c.PropertyName).ToList();
     SortOrders = visibleColumns.Select(c => c.SortOrder).ToList();
     RelativeColumnsWidth = visibleColumns.Select(c => c.RelativeWidth).ToList();
 }
示例#17
0
 public void ApplyToGrid(FastGrid.FastGrid grid)
 {
     var titles = Titles;
     var columns = new List<FastColumn>();
     // видимость колонок
     foreach (var column in grid.Columns)
     {
         if (!titles.Contains(column.PropertyName))
             column.Visible = false;
         columns.Add(column);
     }
     // порядок колонок
     for (var titleIndex = titles.Count - 1; titleIndex >= 0; titleIndex--)
     {
         var columnIndex = columns.FindIndex(c => c.PropertyName == titles[titleIndex]);
         if (columnIndex == -1)
             continue;
         var column = columns[columnIndex];
         columns.RemoveAt(columnIndex);
         columns.Insert(0, column);
     }
     // проверка на правильность настроек
     var allCorrect = titles.All(title => grid.Columns.Any(c => c.PropertyName == title));
     if (allCorrect && columns.Any(c => c.Visible)) // не допускать невидимости всех колонок
         grid.Columns = columns;
     else
         grid.Columns.ForEach(c => c.Visible = true);
     // сортировка записей по отдельным колонкам
     var orders = SortOrders;
     if (orders != null)
         for (var i = 0; i < orders.Count; i++)
         {
             if (i >= grid.Columns.Count)
                 break;
             grid.Columns[i].SortOrder = orders[i];
         }
     // установка относительной ширины
     var relativeColumnsWidth = RelativeColumnsWidth;
     if (relativeColumnsWidth != null)
         for (var i = 0; i < relativeColumnsWidth.Count; i++)
         {
             if (i >= grid.Columns.Count)
                 break;
             grid.Columns[i].RelativeWidth = relativeColumnsWidth[i];
         }
 }
示例#18
0
        /// <summary>
        /// Предустановка столбцов таблицы по сделкам
        /// </summary>
        public static void SetupDealsGrid(FastGrid.FastGrid grid, bool isClosedDealsTable)
        {
            var blankMarketOrder = new MarketOrder();
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.ID), "#") {ColumnWidth = 50});
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.Symbol), Localizer.GetString("TitleInstrument")) {ColumnWidth = 70});
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.Side), Localizer.GetString("TitleType"))
                {
                    ColumnWidth = 60,
                    formatter = s => (int) s < 0 ? "SELL" : "BUY"
                });
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.Volume), Localizer.GetString("TitleVolume"))
                {
                    ColumnWidth = 82,
                    formatter = value => ((int) value).ToStringUniformMoneyFormat()
                });
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.PriceEnter), Localizer.GetString("TitleEnter"))
                {
                    ColumnWidth = 64,
                    formatter = p => ((float) p).ToStringUniformPriceFormat()
                });
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.TimeEnter), Localizer.GetString("TitleEnterTime"))
                {
                    ColumnWidth = 82
                });
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.PriceExit), Localizer.GetString("TitleExit"))
                {
                    ColumnWidth = 64,
                    formatter = p => p == null ? "" : ((float) p).ToStringUniformPriceFormat()
                });
            grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.ResultBase), Localizer.GetString("TitleResultInUSDShort"))
                {
                    ColumnWidth = 82,
                    formatter = p => p == null ? "" : ((float) p).ToStringUniformPriceFormat()
                });
            if (isClosedDealsTable)
            {
                grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.TimeExit), Localizer.GetString("TitleExitTime"))
                    {
                        ColumnMinWidth = 160
                    });
                grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.ResultDepo), Localizer.GetString("TitleResult"))
                    {
                        ColumnMinWidth = 65,
                        formatter = value => ((float) value).ToStringUniformMoneyFormat(),
                        colorColumnFormatter = (object value, out Color? color, out Color? fontColor) =>
                            {
                                color = null;
                                fontColor = null;
                                if (value == null) return;
                                var rst = (float) value;
                                fontColor = rst < -0.9f ? Color.Red : rst < 1 ? Color.Black : Color.Blue;
                            }
                    });
            }
            else
            {
                grid.Columns.Add(new FastColumn(blankMarketOrder.Property(p => p.ResultPoints), Localizer.GetString("TitlePoints"))
                    {
                        ColumnMinWidth = 65,
                        formatter = value => ((float) value).ToStringUniformMoneyFormat(true),
                        colorColumnFormatter = (object value, out Color? color, out Color? fontColor) =>
                            {
                                color = null;
                                fontColor = null;
                                if (value == null) return;
                                var rst = (float) value;
                                fontColor = rst < -0.9f ? Color.Red : rst < 1 ? Color.Black : Color.Blue;
                            }
                    });
            }

            grid.FontAnchoredRow = new Font(grid.Font, FontStyle.Bold);
            grid.CheckSize(true);
            grid.CalcSetTableMinWidth();
            grid.ContextMenuRequested += OrdersFastGridContextMenuRequested;
        }
示例#19
0
        public static void RebindStatisticsFastGrid(FastGrid.FastGrid grid, PerformerStat performer, AccountEfficiency efficiency)
        {
            if (performer == null)
                return;
            var singleValueData = new List<TradeSharp.Util.Cortege2<string, string>>();
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleProfitInPercents"),
                    b = performer.Profit.ToString("f2")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleDealsTotal"),
                    b = performer.DealsCount.ToStringUniformMoneyFormat()
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleMaximumRelativeDrawdownInPercents"),
                    b = performer.MaxRelDrawDown.ToString("N2")
                });

            if (efficiency != null) // при получении всех сделок
            {
                singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleProfitableDealCount"),
                    b = (efficiency.closedDeals.Count(d => d.ResultDepo > 0) +
                         efficiency.openedDeals.Count(d => d.ResultDepo > 0)).ToStringUniformMoneyFormat()
                });
                singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleLosingDealCount"),
                    b = (efficiency.closedDeals.Count(d => d.ResultDepo < 0) +
                         efficiency.openedDeals.Count(d => d.ResultDepo < 0)).ToStringUniformMoneyFormat()
                });
                singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                    {
                        a = Localizer.GetString("TitleDealsOpened"),
                        b = efficiency.DealsStillOpened.ToStringUniformMoneyFormat()
                    });
            }

            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleRatioOfAverageProfitToAverageLossShort"),
                    b = performer.GreedyRatio.ToString("N2")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleMaximumLeverage"),
                    b = performer.MaxLeverage.ToString("N2")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleProfitForNMonthsInPercents"),
                    b = performer.ProfitLastMonths.ToString("f2")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleGAAnnualProfitInPercentsShort"),
                    b = performer.AvgYearProfit.ToString("N3")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleSharpeRatioShort"),
                    b = performer.Sharp.ToString("N2")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleSubscriberCount"),
                    b = performer.SubscriberCount.ToString("d")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleFundsUnderManagementShort") + ", " + performer.DepoCurrency,
                    b = performer.Equity.ToStringUniformMoneyFormat()
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleRatingFS"),
                    b = performer.Score.ToString("f2")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleTradeTimeInDays"),
                    b = performer.DaysTraded.ToString("d")
                });
            singleValueData.Add(new TradeSharp.Util.Cortege2<string, string>
                {
                    a = Localizer.GetString("TitleProfitInPoints"),
                    b = performer.SumProfitPoints.ToStringUniformMoneyFormat(false)
                });
            grid.DataBind(singleValueData);

            // для удобочитаемости первая колонка сохраняет первоначальную минимальную ширину
            var skippedColumns = grid.Columns.Where(c => c.PropertyName == "a").ToList();
            var minWidths = skippedColumns.ToDictionary(c => c, c => c.ColumnMinWidth);
            grid.CheckSize(true);
            skippedColumns.ForEach(c => c.ColumnMinWidth = minWidths[c]);
            grid.Invalidate();
        }
示例#20
0
 public static void GridSummaryStatUserDrawCellText(int columnIndex, FastColumn column, FastCell cell,
                                              FastGrid.BrushesStorage brushes, Graphics g, Point leftTop,
                                              int cellWidth, int cellHeight, Font font, Brush brushFont,
                                              Color? fontColor, int rowIndex, int cellPadding)
 {
     var cellString = cell.CellString;
     var cellFont = column.ColumnFont ?? font;
     var brush = brushFont;
     if (fontColor.HasValue)
         brush = brushes.GetBrush(fontColor.Value);
     var leftString = cellString;
     var rightString = "";
     if (cellString.IndexOf('\t') != -1)
     {
         leftString = cellString.Substring(0, cellString.IndexOf('\t'));
         rightString = cellString.Substring(cellString.IndexOf('\t') + 1);
     }
     g.DrawString(leftString, cellFont, brush,
                  leftTop.X + cellPadding, leftTop.Y + cellHeight / 2,
                  new StringFormat {Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center});
     g.DrawString(rightString, cellFont, brush,
                  leftTop.X + cellWidth - cellPadding, leftTop.Y + cellHeight / 2,
                  new StringFormat {Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Center});
 }