Exemple #1
0
        private static void OnExportGridCommand(XamDataGrid parameter)
        {
            //Argument.IsNotNull(() => parameter);

            //IExceptionService exceptionService = ServiceLocator.Default.ResolveType<IExceptionService>();
            //var grid = parameter;

            //grid.IsBusy = true;

            //Workbook workbookAspose = ExportWorkbook.Export(grid);

            //string filename = ExportHelper.AddIndexToFileNameIfNeeded();

            //try
            //{
            //    workbookAspose.Save(filename);

            //    System.Diagnostics.Process.Start(filename);
            //}
            //catch (Exception ex)
            //{
            //    exceptionService.HandleException(ex);
            //}
            //finally
            //{
            //    grid.IsBusy = false;
            //}
        }
Exemple #2
0
        /*
         * public event PropertyChangedEventHandler PropertyChanged;
         * protected void RaisePropertyChanged(string name)
         * {
         *  PropertyChangedEventHandler handler = PropertyChanged;
         *  if (handler != null) handler(this, new PropertyChangedEventArgs(name));
         * }
         * public vmDbFilter()
         * {
         *  cnn = new OracleConnection(cnnString);
         *  cnn.Open();
         * }
         */



        public void setFilter(string sql, XamDataGrid xDG, DbConnection cnn, MyDb.Common.DataBaseType cnnType)
        {
            _BasicQuery = sql; _cnn = cnn; _xDG = xDG; _cnnType = cnnType;
            setFields();
            //FcItems = new ObservableCollection<FilterItem>();
            lbMain.DataContext = DataContext;//lbMain.ItemsSource = FcItems;
            addFilterItem();
            //fi.Field = fiel
            if (_viewModel.FilterItems.Count > 0)                     ///if (FcItems.Count > 0)
            {
                lbMain.ScrollIntoView(_viewModel.FilterItems.Last()); //FcItems.Last());
                Infragistics.Controls.Editors.XamMultiColumnComboEditor ce = null;
                //lbMain.Items.MoveCurrentToFirst();
                int pos = 0;
                lbMain.SelectedIndex = pos;
                //ListBoxItem item = lbMain.ItemContainerGenerator.ContainerFromIndex(pos) as ListBoxItem;
                //try { ce = VisualTree.FindFirstElementInVisualTree<Infragistics.Controls.Editors.XamMultiColumnComboEditor>(lbMain); } catch { }
                if (ce != null && ce.Items.Count > 0)
                {
                    ce.SelectedIndex = 0;
                }
            }
            //    new FilterItem()
            // lbMain.Items.Refresh();
        }
        private void AssociatedObject_Drop(object sender, DropEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Drop");

            DragSource       dragSource = sender as DragSource;
            FrameworkElement fe         = dragSource.AssociatedObject as FrameworkElement;
            Record           record     = fe.DataContext as Record;

            // XamDataGrid の取得
            XamDataGrid presenter = record.DataPresenter as XamDataGrid;

            // ドラッグレコードの取得
            ContentPresenter source       = e.DragSource as ContentPresenter;
            DataRecord       sourceRecord = source.DataContext as DataRecord;
            int sourceIndex = sourceRecord.Index;

            // ドロップレコードの取得
            ContentPresenter target       = e.DropTarget as ContentPresenter;
            DataRecord       targetRecord = target.DataContext as DataRecord;
            int targetIndex = targetRecord.Index;

            var dc = presenter.DataContext;
            var vm = dc as MainWindowViewModel;

            // ドラッグレコードの位置変更
            //vm.Tasks.Move(sourceIndex, targetIndex);
        }
Exemple #4
0
        public static GridCustomizations GetGridExternalInformations(XamDataGrid grid)
        {
            var gridCustomizations = new GridCustomizations();

            foreach (var field in grid.FieldLayouts[0].Fields)
            {
                //field.Name
                if (field.CellValuePresenterStyle?.Setters?.Count > 0)
                {
                    ColumnSettings columnSettings = new ColumnSettings();

                    foreach (Setter r in field.CellValuePresenterStyle.Setters)
                    {
                        if (r.Property.Name == Constants.ForegroundKey)
                        {
                            columnSettings.ForeColor = r.Value.ToString();
                        }
                        else if (r.Property.Name == Constants.BackgroundKey)
                        {
                            columnSettings.BackGroundColor = r.Value.ToString();
                        }
                    }

                    if (columnSettings.HasData)
                    {
                        gridCustomizations.ColumnsStyle[field.Name] = columnSettings;
                    }
                }
            }

            return(gridCustomizations);
        }
Exemple #5
0
        private void xamDataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            XamDataGrid xdg = xamDataGrid;

            MarkAddNewRecord((DataRecord)xamDataGrid.Records[0]);

            // mark AddRecord for each Indicator and CompoundPlate list
            foreach (DataRecord rec in xamDataGrid.Records) // step through all methods
            {
                if (rec.HasChildren)                        // if the method has children
                {
                    foreach (ExpandableFieldRecord expRecord in rec.ChildRecords)
                    {
                        // get first record and mark as "AddRecord"
                        DataRecord addRecord = (DataRecord)(expRecord.ChildRecords[0]);

                        if (addRecord.DataItem.GetType() == typeof(IndicatorItem))
                        {
                            MarkAddNewRecord(addRecord);
                        }
                        else if (addRecord.DataItem.GetType() == typeof(CompoundPlateItem))
                        {
                            MarkAddNewRecord(addRecord);
                        }
                    }
                }
            }
        }
Exemple #6
0
        public Task RestoreGrid(XamDataGrid grid)
        {
            return(null);
            //var str = File.ReadAllText(GridLayout);

            //byte[] bytes = Encoding.UTF8.GetBytes(str);

            //return dispatcherService.InvokeAsync(() =>
            //{
            //    using (var memoryStream = new MemoryStream(bytes))
            //    {
            //        grid.LoadCustomizations(memoryStream);
            //        timer.Start();
            //        dispatcherTimer.Start();
            //    }


            //    //grid customizations
            //    var customizations = File.ReadAllText(GridCustomizations);

            //    byte[] bytesCustomizations = Encoding.UTF8.GetBytes(customizations);


            //    using (var ms = new MemoryStream(bytesCustomizations))
            //    {
            //        IXmlSerializer x = ServiceLocator.Default.ResolveType<IXmlSerializer>();

            //        GridCustomizations c = x.Deserialize(typeof(GridCustomizations), ms) as GridCustomizations;

            //        LoadCustomGridSettings(grid, c);

            //    }
            //});
        }
Exemple #7
0
        public Task PersistGrid(XamDataGrid grid)
        {
            return(dispatcherService.InvokeAsync(() =>
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    grid.SaveCustomizations(memoryStream);

                    byte[] bytes = memoryStream.ToArray();

                    var str = Encoding.UTF8.GetString(bytes);

                    var externalInformations = GetGridExternalInformations(grid);



                    //    using (var ms = new MemoryStream())
                    //    {
                    //        x.Serialize(externalInformations, ms);

                    //        byte[] bytes2 = ms.ToArray();
                    //                var str1 = Encoding.UTF8.GetString(bytes2);

                    //    File.WriteAllText(File, str1);
                    //}

                    //File.WriteAllText(GridLayout, str);
                }
            }));
        }
Exemple #8
0
        private Task OnLoadCommandExecute(XamDataGrid grid)
        {
            timer.Stop();
            dispatcherTimer.Stop();

            return(gridPersistenceService.RestoreGrid(grid));
        }
Exemple #9
0
        private void OnRemovePortfolio(XamDataGrid dataGrid)
        {
            if (dataGrid == null)
            {
                return;
            }

            DataRecord dr = dataGrid.ActiveRecord as DataRecord;

            if (dr != null)
            {
                PortfolioVM portfVm = dr.DataItem as PortfolioVM;
                if (portfVm != null)
                {
                    MessageBoxResult res = MessageBox.Show(Application.Current.MainWindow,
                                                           string.Format("删除帐户[{0}]的组合 {1}", portfVm.AccountId, portfVm.DisplayText),
                                                           "删除确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (res == MessageBoxResult.Yes)
                    {
                        RemovePortfolio(portfVm);
                        if (_client.IsConnected)
                        {
                            _client.RemovePortf(portfVm.Id);
                        }

                        PublishChanged();
                    }
                }
            }
        }
Exemple #10
0
        private void LoadCustomGridSettings(XamDataGrid grid, GridCustomizations gridCustomizations)
        {
            foreach (var gridCustomization in gridCustomizations.ColumnsStyle.Where(x => x.Value.HasData))
            {
                string columnName = gridCustomization.Key;

                var column = grid.FieldLayouts[0].Fields.FirstOrDefault(x => x.Name == columnName);

                var style = new Style(typeof(CellValuePresenter));

                if (!string.IsNullOrEmpty(gridCustomization.Value.ForeColor))
                {
                    style.Setters.Add(new Setter(Control.ForegroundProperty,
                                                 new SolidColorBrush((Color)ColorConverter.ConvertFromString(gridCustomization.Value.ForeColor))));
                }

                if (!string.IsNullOrEmpty(gridCustomization.Value.BackGroundColor))
                {
                    style.Setters.Add(new Setter(Control.BackgroundProperty,
                                                 new SolidColorBrush((Color)ColorConverter.ConvertFromString(gridCustomization.Value.BackGroundColor))));
                }

                column.CellValuePresenterStyle = style;
            }
        }
Exemple #11
0
        private async Task OnSaveCommandExecute(XamDataGrid grid)
        {
            timer.Stop();
            dispatcherTimer.Stop();

            await gridPersistenceService.PersistGrid(grid);

            timer.Start();
            dispatcherTimer.Start();
        }
Exemple #12
0
        public static Record GetActiveRecord(this XamDataGrid control)
        {
            Record activeRecord = null;

            if (control.Records != null && control.Records.Count > 0)
            {
                activeRecord = control.Records[0];
            }

            return(activeRecord);
        }
Exemple #13
0
        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            Key key = e.Key;

            if (key == Key.Delete)
            {
                // Delete the selected record
                var      emp = xamDataGrid1.ActiveRecord as DataRecord;
                Employee p   = emp.DataItem as Employee;

                XamDataGrid dg = sender as XamDataGrid;
                var         dd = dg.DataSource as BindingList <Employee>;

                dd.Remove(p);
            }
        }
Exemple #14
0
        private void PopulateCombo(XamDataGrid grid)
        {
            try
            {
                var cbJ = (ComboBoxField)grid.DefaultFieldLayout.Fields[DictionaryMain.KolumnaJm];
                var cbV = (ComboBoxField)grid.DefaultFieldLayout.Fields[DictionaryMain.KolumnaStawkaVat];
                var cbN = (ComboBoxField)grid.DefaultFieldLayout.Fields[DictionaryMain.KolumnaTowar];

                cbJ.ItemsSource = Jednostka.Rows.Cast <DataRow>().Select(s => s[1]).ToList();
                cbV.ItemsSource = StawkaVat.Rows.Cast <DataRow>().Select(s => s[1]).ToList();
                cbN.ItemsSource = Usluga.Rows.Cast <DataRow>().Select(s => s[1]).ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
Exemple #15
0
        public static void ConfigureGrid(XamDataGrid dataGrid, DataTableEx userTable, enumTimeDiscreteType discreteType, enumTypeInformation typeInformation,
                                         string format, bool isHalfhours, bool isCumulateDrums = false, bool isDateTimeGroupingGridControlXam = true, bool useBindedConverter = true)
        {
            if (dataGrid == null || userTable == null)
            {
                return;
            }

            var view = userTable.DefaultView;

            try
            {
                dataGrid.BeginInit();
                dataGrid.FieldSettings.AllowEdit = false;

                view.AllowDelete = view.AllowEdit = view.AllowNew = false;

                //var style = new Style(typeof(XamNumericEditor));
                //style.Setters.Add(new Setter(ValueEditor.FormatProperty, format));

                if (isHalfhours)
                {
                    SetHalfhoursColumnsForXamDataGrid(dataGrid, userTable, discreteType, typeInformation, format, isCumulateDrums, isDateTimeGroupingGridControlXam, useBindedConverter);
                }
                else
                {
                    SetValidateColumnsForXamDataGrid(dataGrid, userTable);
                }

                //view.Table = null;
            }
            finally
            {
                dataGrid.DataSource = view;
                dataGrid.EndInit();
            }

            //dataGrid.Dispatcher.BeginInvoke((System.Action) (() =>
            //{

            //}), DispatcherPriority.Background);
        }
Exemple #16
0
        // ReSharper disable once UnusedMethodReturnValue.Local
        private static bool CanExecuteExportGrid(XamDataGrid parameter)
        {
            Argument.IsNotNull(() => parameter);

            return(parameter.DataItems.Count > 0);
        }
Exemple #17
0
        static void SetHalfhoursColumnsForXamDataGrid(XamDataGrid dataGrid, DataTableEx userTable,
                                                      enumTimeDiscreteType discreteType, enumTypeInformation typeInformation, string format, bool isCumulateDrums
                                                      , bool isDateTimeGroupingGridControlXam, bool useBindedConverter)
        {
            //var nameStyle = dataGrid.FindResource("TIChanelName") as Style;

            ////Style labelStyle = null;

            try
            {
                var labelStyle = dataGrid.FindResource("LabelObjectStyle") as Style;
                dataGrid.FieldSettings.LabelPresenterStyle = labelStyle;
            }
            catch
            {
            }

            //var vTemplate = dataGrid.FindResource("FValueTemplate") as DataTemplate;
            var fValueNoBindMeasureStyle = dataGrid.FindResource("FValueNoBindMeasureStyle") as Style;

            var vFreeHierarchyObjectTemplate = Application.Current.FindResource("FreeHierarchyObjectTemlate") as DataTemplate;
            var fValueStyle = useBindedConverter ?  dataGrid.FindResource("FValueStyle") as Style : fValueNoBindMeasureStyle;

            var widthValue    = new FieldLength(105);
            var widthFreeHier = new FieldLength(270);

            var comparer = new IFValueComparer();

            var measure = dataGrid.FindParent <IMeasure>();

            dataGrid.Resources["IMeasure"] = measure;

            //var fConverter = new FValueConverter
            //{
            //    FParameter = new FValueParameter
            //    {
            //        Measure = measure,
            //    }
            //};

            var fieldLayout = dataGrid.FieldLayouts[0];
            var fields      = fieldLayout.Fields;

            try
            {
                fields.BeginUpdate();
                //fieldLayout.SortedFields.BeginUpdate();

                var dtCol = userTable.Columns["EventDateTime"];

                var dtField = new TemplateField
                {
                    Name          = dtCol.ColumnName,
                    DataType      = dtCol.DataType,
                    Label         = dtCol.Caption,
                    Width         = new FieldLength(95),
                    AllowFixing   = AllowFieldFixing.Default,
                    FixedLocation = FixedFieldLocation.FixedToNearEdge,
                    Settings      =
                    {
                        LabelPresenterStyle = dataGrid.FindResource("TimeStyle") as Style
                    }
                };

                fields.Add(dtField);

                if (isCumulateDrums)
                {
                    //dtField.Settings.CellValuePresenterStyle =
                    //    XamDataGridHelper.DataTemplateToCellValuePresenterStyle(ConstantHelper.DateTimeTemplateName);
                    dtField.DisplayTemplate = Application.Current.Resources[ConstantHelper.DateTimeTemplateName] as DataTemplate;
                }
                else
                {
                    string dataTemplateToCellValuePresenterStyleName;
                    //-------------------------------
                    switch (discreteType)
                    {
                    case enumTimeDiscreteType.DBHalfHours:
                        dataTemplateToCellValuePresenterStyleName = ConstantHelper.HalfHourstoRangeTimeTemplateName;
                        break;

                    case enumTimeDiscreteType.DBHours:
                        dataTemplateToCellValuePresenterStyleName = ConstantHelper.HourstoRangeTimeTemplateName;
                        break;

                    case enumTimeDiscreteType.DB24Hour:
                        dataTemplateToCellValuePresenterStyleName = ConstantHelper.DateTemplateName;
                        break;

                    case enumTimeDiscreteType.DBMonth:
                        dataTemplateToCellValuePresenterStyleName = ConstantHelper.MonthName;
                        break;

                    default:
                        dataTemplateToCellValuePresenterStyleName = ConstantHelper.DateTimeTemplateName;
                        break;
                    }

                    dtField.Tag             = dataTemplateToCellValuePresenterStyleName; //Это нужно для форматирования при выгрузке в Excel
                    dtField.DisplayTemplate = Application.Current.Resources[dataTemplateToCellValuePresenterStyleName] as DataTemplate;

                    //dtField.Settings.CellValuePresenterStyle =
                    //    XamDataGridHelper.DataTemplateToCellValuePresenterStyle(
                    //        dataTemplateToCellValuePresenterStyleName);
                }

                dtField.Label = "Время";

                if (discreteType == enumTimeDiscreteType.DB24Hour)
                {
                    dtField.Settings.GroupByMode = FieldGroupByMode.Month;
                    dtField.Settings.GroupByRecordPresenterStyle =
                        Application.Current.FindResource("MonthYearXamDataGridStyle") as Style;
                }
                else
                {
                    dtField.Settings.GroupByMode = FieldGroupByMode.Date;
                }


                SummaryCalculator statType;
                string            prefix;
                if (typeInformation == enumTypeInformation.Power)
                {
                    statType = new FValueAvgCalculator(format);
                    prefix   = "Сред:";
                }
                else
                {
                    statType = new FValueSumCalculator(format);
                    prefix   = "Сум:";
                }

                var stringFormat = prefix + " {0:" + format + "}";

                var dfc = new DetailFieldInfoEqualityComparer();

                //FieldGroup fieldGroupByObject = null;
                //FieldGroup fieldGroupByMeasureCategory = null;
                //EnumMeasureUnitCategory? previousMeasureCategory = null; //Для определения групповать или нет по категории

                foreach (var colGroupByObject in userTable.Columns
                         .Cast <DataColumn>()
                         .Where(c => c.ColumnName != "EventDateTime")
                         .Select(c =>
                {
                    DetailFieldInfo fieldInfo;
                    userTable.TryGetIndexByItemName(c.ColumnName, out fieldInfo);

                    return(new Tuple <DetailFieldInfo, DataColumn>(fieldInfo, c));
                })
                         .GroupBy(c => c.Item1, dfc))
                {
                    if (colGroupByObject.Key == null || (colGroupByObject.Key.ChannelType == 0 && colGroupByObject.Key.ColumnType == EnumColumnType.None))
                    {
                        //Группировать не нужно
                        foreach (var colByObject in colGroupByObject)
                        {
                            DetailFieldInfo fieldInfo;
                            userTable.ItemsIndexesDict.TryGetValue(colByObject.Item2.ColumnName, out fieldInfo);

                            SummaryDefinition summaryDefinition;
                            var fld = AddFieldAndSummary(colByObject.Item2, widthValue, comparer, fieldInfo != null && fieldInfo.UseMeasureModule,
                                                         isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle);

                            fld.Label = fieldInfo == null ? colByObject.Item2.Caption : (object)colByObject.Item1;
                            fields.Add(fld);
                            if (summaryDefinition != null)
                            {
                                fieldLayout.SummaryDefinitions.Add(summaryDefinition);
                            }
                        }
                    }
                    //else if ()
                    //{
                    //    //Группируем по типу
                    //    foreach (var colByObjectByColumnType in colGroupByObject.GroupBy(c => c.Item1.ColumnType))
                    //    {
                    //        foreach (var colByObject in colByObjectByColumnType)
                    //        {
                    //            DetailFieldInfo fieldInfo;
                    //            if (!userTable.ItemsIndexesDict.TryGetValue(colByObject.Item2.ColumnName, out fieldInfo)) continue;

                    //            FValueSummaryDefinition summaryDefinition;
                    //            var fld = AddFieldAndSummary(colByObject.Item2, widthValue, comparer, fieldInfo != null && fieldInfo.UseMeasureModule,
                    //                isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle);

                    //            fld.Label = fieldInfo == null ? colByObject.Item2.Caption : (object)colByObject.Item1;
                    //            fields.Add(fld);
                    //            if (summaryDefinition != null)
                    //            {
                    //                fieldLayout.SummaryDefinitions.Add(summaryDefinition);
                    //            }
                    //        }
                    //    }
                    //}
                    else
                    {
                        var fieldInfo          = colGroupByObject.Key;
                        var fieldGroupByObject = new FieldGroup
                        {
                            Label = fieldInfo.Id,
                        };

                        fieldLayout.FieldItems.Add(fieldGroupByObject);

                        //Группируем по ед.измерения
                        foreach (var colGroupByMeasureCategory in colGroupByObject.GroupBy(c => c.Item1.MeasureUnitUn.SubstringQuantityUn()))
                        {
                            var colGroupByMeasureCategoryList = colGroupByMeasureCategory.ToList();

                            if (!string.IsNullOrEmpty(colGroupByMeasureCategory.Key) && colGroupByMeasureCategoryList.Count > 1)
                            {
                                //Есть категории ед. измерения и их несколько
                                var fieldGroupByMeasureCategory = new FieldGroup
                                {
                                    Label = new LabelMeasureQuantity
                                    {
                                        MeasureQuantityType_UN = colGroupByMeasureCategory.Key,
                                    },
                                };

                                fieldGroupByObject.Children.Add(fieldGroupByMeasureCategory);

                                foreach (var colByMeasure in colGroupByMeasureCategoryList)
                                {
                                    SummaryDefinition summaryDefinition;
                                    var fld = AddFieldAndSummary(colByMeasure.Item2, widthValue, comparer, fieldInfo.UseMeasureModule,
                                                                 isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle);

                                    fld.Label = colByMeasure.Item1;
                                    fieldGroupByMeasureCategory.Children.Add(fld);
                                    if (summaryDefinition != null)
                                    {
                                        fieldLayout.SummaryDefinitions.Add(summaryDefinition);
                                    }
                                }
                            }
                            else
                            {
                                var fielgGroupByReplacedTiDict = new Dictionary <string, FieldGroup>();

                                //Нет категорий, или она одна
                                foreach (var colByMeasure in colGroupByMeasureCategoryList)
                                {
                                    if (colByMeasure.Item2.ColumnName.StartsWith("ovInfo"))
                                    {
                                        var hoc = new HierObjectsConverterComparer();

                                        //var fld = AddField(colByMeasure.Item2, widthFreeHier, hoc, fieldInfo.UseMeasureModule,
                                        //    vFreeHierarchyObjectTemplate,
                                        //    vFreeHierarchyObjectTemplate, new HierObjectsConverter(), null);

                                        var fld = new TemplateField
                                        {
                                            Name            = colByMeasure.Item2.ColumnName,
                                            DataType        = colByMeasure.Item2.DataType,
                                            Width           = widthFreeHier,
                                            AllowFixing     = AllowFieldFixing.No,
                                            DisplayTemplate = vFreeHierarchyObjectTemplate,
                                            Settings        =
                                            {
                                                AutoSizeOptions      = FieldAutoSizeOptions.None,
                                                Width                = widthFreeHier,
                                                SummaryUIType        = SummaryUIType.MultiSelect,
                                                FilterComparer       = hoc,
                                                FilterOperandUIType  = FilterOperandUIType.Combo,
                                                AllowRecordFiltering = true,
                                            },
                                            HorizontalContentAlignment = HorizontalAlignment.Stretch,
                                            VerticalContentAlignment   = VerticalAlignment.Stretch,
                                        };

                                        fld.Label = "Замещаемые ТИ";
                                        fld.Settings.FilterOperandUIType         = FilterOperandUIType.DropDownList;
                                        fld.Settings.FilterLabelIconDropDownType = FilterLabelIconDropDownType.MultiSelectExcelStyle;
                                        fld.Settings.GroupByComparer             = hoc;

                                        //fld.ValueToTextConverter = new HierObjectsConverter();
                                        fld.Settings.FilterComparer = new HierObjectsConverterComparer();
                                        fieldGroupByObject.Children.Add(fld);
                                    }
                                    else
                                    {
                                        FieldGroup fielgGroupByReplacedTi = null;

                                        //Группируем по замещаемой ТИ
                                        if (colByMeasure.Item2.ColumnName.StartsWith("ovValue") &&
                                            !fielgGroupByReplacedTiDict.TryGetValue(
                                                colByMeasure.Item1.GroupByReplacedTiName, out fielgGroupByReplacedTi))
                                        {
                                            fielgGroupByReplacedTi = new FieldGroup
                                            {
                                                Label = colByMeasure.Item1.ReplacedId,
                                            };

                                            fielgGroupByReplacedTiDict[colByMeasure.Item1.GroupByReplacedTiName] =
                                                fielgGroupByReplacedTi;
                                        }

                                        SummaryDefinition summaryDefinition;
                                        Field             fld;

                                        if (!string.IsNullOrEmpty(colByMeasure.Item1.MeasureUnitUn) && colByMeasure.Item1.MeasureUnitUn.IndexOf("RatioUnit") > -1)
                                        {
                                            //Это %, нужно усреднять
                                            fld = AddFieldAndSummary(colByMeasure.Item2, widthValue, comparer, colByMeasure.Item1.UseMeasureModule,
                                                                     isCumulateDrums, new FValueAvgCalculator(format), "Сред: {0:" + format + "}", out summaryDefinition, fValueNoBindMeasureStyle);
                                        }
                                        else
                                        {
                                            fld = AddFieldAndSummary(colByMeasure.Item2, widthValue, comparer, useBindedConverter && colByMeasure.Item1.UseMeasureModule,
                                                                     isCumulateDrums, statType, stringFormat, out summaryDefinition, fValueStyle);
                                        }

                                        fld.Label = colByMeasure.Item1;

                                        if (fielgGroupByReplacedTi != null)
                                        {
                                            fielgGroupByReplacedTi.Children.Add(fld);
                                        }
                                        else
                                        {
                                            fieldGroupByObject.Children.Add(fld);
                                        }

                                        if (summaryDefinition != null)
                                        {
                                            fieldLayout.SummaryDefinitions.Add(summaryDefinition);
                                        }

                                        if (colByMeasure.Item1.IsOv)
                                        {
                                            //Если это ОВ, добавляем суммарную информацию о неразнесенных значениях
                                            var unWritedOvs = new FValueSummaryDefinition
                                            {
                                                SourceFieldName  = colByMeasure.Item2.ColumnName,
                                                Calculator       = new FValueSumUnreplacedCalculator(format),
                                                StringFormat     = stringFormat,
                                                UseMeasureModule = fieldInfo.UseMeasureModule,
                                            };

                                            fieldLayout.SummaryDefinitions.Add(unWritedOvs);
                                        }
                                    }
                                }

                                if (fielgGroupByReplacedTiDict.Count > 0)
                                {
                                    fieldGroupByObject.Children.AddRange(fielgGroupByReplacedTiDict.Values);
                                }
                            }
                        }
                    }
                }

                if (isDateTimeGroupingGridControlXam)
                {
                    //dtField.Settings.AllowSummaries = false;
                    dtField.Settings.AllowGroupBy = true;


                    fieldLayout.SortedFields.Add(new FieldSortDescription("EventDateTime", ListSortDirection.Ascending,
                                                                          true));
                }
                else if (discreteType != enumTimeDiscreteType.DBMonth && discreteType != enumTimeDiscreteType.DB24Hour)
                {
                    dtField.DisplayTemplate = Application.Current.Resources[ConstantHelper.DateTimeTemplateName] as DataTemplate;
                }

                //var consumptionScheduleField = fields.FirstOrDefault(ff => ff.Name == "ConsumptionSchedule");
                //if (consumptionScheduleField != null)
                //{
                //    consumptionScheduleField.Label = "Тип. потр.";
                //}

                //var consumptionSchedulePercentField = fields.FirstOrDefault(ff => ff.Name == "ConsumptionSchedulePercent");
                //if (consumptionSchedulePercentField != null)
                //{
                //    consumptionSchedulePercentField.Label = "Тип. потр. %";
                //}
            }
            finally
            {
                // fieldLayout.SortedFields.EndUpdate();
                fields.EndUpdate();
            }

            //XamDataGridHelper.ConfigureGrid(dataGrid, true, false, true, true, true);
            dataGrid.FieldLayoutSettings.FixedFieldUIType = FixedFieldUIType.Splitter;

            dataGrid.FieldSettings.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed;

            if (userTable.Columns.Count < 20)
            {
                //из-за того что тормоза ограничиваем
                //dataGrid.FieldSettings.SummaryDisplayArea = dataGrid.FieldSettings.SummaryDisplayArea | SummaryDisplayAreas.InGroupByRecords;
            }

            if (userTable.Columns.Count < 1000)
            {
                dataGrid.RecordsInViewChanged += ExpandFirstRecord;
            }
        }
Exemple #18
0
        static void SetValidateColumnsForXamDataGrid(XamDataGrid dataGrid, DataTableEx userTable)
        {
            var hierObjectStyle = dataGrid.FindResource("HierObjectStyle") as Style;
            var hTemplate       = dataGrid.FindResource("HierarchyObjectTemplate") as DataTemplate;
            var chTemplate      = dataGrid.FindResource("ChannelTemplate") as DataTemplate;
            var fFlagStyle      = dataGrid.FindResource("FFlagStyle") as Style;

            dataGrid.FieldSettings.LabelPresenterStyle = dataGrid.FindResource("ValidLabelStyle") as Style;
            // dataGrid.BeginInit();

            //var leftHorizontalStyle = dataGrid.FindResource("FastHorizontalLeftCellValuePresenterStyle") as Style;

            var fieldLayout = dataGrid.FieldLayouts[0];
            var fields      = fieldLayout.Fields;

            //var field = fieldLayout.Fields["NameTI"] as TemplateField;
            try
            {
                fields.BeginUpdate();

                #region Вспомогательные поля

                var comparer = new IFreeHierarchyObjectComparer();

                var tiFld = new Field
                {
                    Name          = "NameTI",
                    DataType      = typeof(IFreeHierarchyObject),
                    Label         = "Объект",
                    Width         = new FieldLength(200),
                    FixedLocation = FixedFieldLocation.FixedToNearEdge,
                    //FixedLocation = FixedFieldLocation.FixedToNearEdge,
                    Settings =
                    {
                        AllowGroupBy              = true,
                        GroupByComparer           = comparer,
                        SortComparer              = comparer,
                        FilterComparer            = comparer,
                        CellVisibilityWhenGrouped = Visibility.Collapsed,
                        FilterOperandUIType       = FilterOperandUIType.DropDownList,
                        AllowFixing             = AllowFieldFixing.Near,
                        AllowEdit               = false,
                        EditorStyle             = null,
                        AllowRecordFiltering    = true,
                        CellValuePresenterStyle = hierObjectStyle,
                    },
                    HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left,
                    VerticalContentAlignment   = VerticalAlignment.Center,
                };

                //if (leftHorizontalStyle != null)
                //{
                //    //Это
                //    tiFld.Settings.CellValuePresenterStyle = leftHorizontalStyle;
                //}

                fields.Add(tiFld);

                fields.Add(new TemplateField
                {
                    Name            = "Channel",
                    Label           = "К",
                    DataType        = typeof(object),
                    DisplayTemplate = chTemplate,
                    Width           = new FieldLength(30),
                    FixedLocation   = FixedFieldLocation.FixedToNearEdge,
                    Settings        = { FilterOperandUIType = FilterOperandUIType.None,
                                        AllowFixing         = AllowFieldFixing.Near,
                                        AllowEdit           = false,
                                        EditorStyle         = null, },
                });

                //fieldLayout.Fields.Add(new TemplateField
                //{
                //    Name = "DataSource",
                //    Label = "Источник данных",
                //    Width = new FieldLength(130),
                //});

                var fld = new Field
                {
                    Name        = "Parent",
                    DataType    = typeof(IFreeHierarchyObject),
                    Label       = "Родитель",
                    Width       = new FieldLength(160),
                    AllowFixing = AllowFieldFixing.Near,
                    //FixedLocation = FixedFieldLocation.FixedToNearEdge,
                    Settings =
                    {
                        //GroupByMode = FieldGroupByMode.Value,
                        AllowGroupBy              = true,
                        GroupByComparer           = comparer,
                        SortComparer              = comparer,
                        FilterComparer            = comparer,
                        CellVisibilityWhenGrouped = Visibility.Collapsed,
                        FilterOperandUIType       = FilterOperandUIType.DropDownList,
                        AllowFixing             = AllowFieldFixing.Near,
                        AllowEdit               = false,
                        EditorStyle             = null,
                        AllowRecordFiltering    = true,
                        CellValuePresenterStyle = hierObjectStyle,
                    },
                    HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left,
                    VerticalContentAlignment   = VerticalAlignment.Center,
                };

                fields.Add(fld);
                var fsd = new FieldSortDescription("Parent", ListSortDirection.Ascending, true);
                fieldLayout.SortedFields.Add(fsd);

                #endregion

                // var flagStyle = XamDataGridHelper.DataTemplateSelectorToCellEditorStyle(flagTemplateSelector, null);

                var width  = new FieldLength(32);
                var height = new FieldLength(20);

                foreach (DataColumn col in userTable.Columns)
                {
                    //var column = fieldLayout.Fields.FirstOrDefault(c => string.Equals(c.Name, "Valid" + i)) as TemplateField;
                    //if (column == null) return;
                    var isValid = col.ColumnName.IndexOf("Valid") >= 0;
                    if (isValid || col.ColumnName.IndexOf("TotalFlag") >= 0)
                    {
                        fields.Add(new Field
                        {
                            Name        = col.ColumnName,
                            DataType    = col.DataType,
                            ToolTip     = col.Caption,
                            Label       = col.Caption,
                            Visibility  = isValid ? Visibility.Visible : Visibility.Collapsed,
                            Width       = width,
                            Height      = height,
                            AllowFixing = AllowFieldFixing.No,
                            AllowResize = false,
                            Settings    =
                            {
                                SummaryUIType               = SummaryUIType.MultiSelect,
                                FilterOperandUIType         = FilterOperandUIType.Combo,
                                FilterOperatorDropDownItems = ComparisonOperatorFlags.None,
                                CellValuePresenterStyle     = fFlagStyle,
                                AllowEdit            = false,
                                AllowRecordFiltering = true,
                                //CellValuePresenterStyle = fFlagStyle,
                            },
                        });
                    }
                }
            }
            finally
            {
                fieldLayout.Fields.EndUpdate();
            }

            //XamDataGridHelper.ConfigureGrid(dataGrid, false, true, false, true, false);

            // раскрываем первую группу
            dataGrid.RecordsInViewChanged += ExpandFirstRecord;
        }
        public static void ConfigureGridDailyIntegrals(XamDataGrid dataGrid, DataTableEx userTable, bool useLossesCoefficient)
        {
            if (dataGrid == null || userTable == null)
            {
                return;
            }

            try
            {
                var labelStyle = dataGrid.FindResource("LabelObjectStyle") as Style;
                dataGrid.FieldSettings.LabelPresenterStyle = labelStyle;
            }
            catch
            {
            }

            var view = userTable.DefaultView;

#if DEBUG
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
#endif

            try
            {
                var hierObjectStyle   = dataGrid.FindResource("HierObjectStyle") as Style;
                var chTemplate        = dataGrid.FindResource("ChannelTemplate") as DataTemplate;
                var fValueStyle       = dataGrid.FindResource("FValueStyle") as Style;
                var fValueNoFlagStyle = dataGrid.FindResource("FValueNoFlagStyle") as Style;
                var widthValue        = new FieldLength(105);

                dataGrid.BeginInit();
                var fieldLayout = dataGrid.FieldLayouts[0];
                var fields      = fieldLayout.Fields;

                try
                {
                    fields.BeginUpdate();

                    #region Создаем основные колонки

                    var comparer = new IFreeHierarchyObjectComparer();

                    fields.Add(new Field
                    {
                        Name        = "Parent",
                        DataType    = typeof(IFreeHierarchyObject),
                        Label       = "Объект",
                        Width       = new FieldLength(160),
                        AllowFixing = AllowFieldFixing.Near,
                        //FixedLocation = FixedFieldLocation.FixedToNearEdge,
                        Settings =
                        {
                            //GroupByMode = FieldGroupByMode.Value,
                            AllowGroupBy              = true,
                            GroupByComparer           = comparer,
                            SortComparer              = comparer,
                            FilterComparer            = comparer,
                            CellVisibilityWhenGrouped = Visibility.Collapsed,
                            FilterOperandUIType       = FilterOperandUIType.DropDownList,
                            AllowFixing             = AllowFieldFixing.Near,
                            AllowEdit               = false,
                            EditorStyle             = null,
                            AllowRecordFiltering    = true,
                            CellValuePresenterStyle = hierObjectStyle,
                        },
                        HorizontalContentAlignment = HorizontalAlignment.Left,
                        VerticalContentAlignment   = VerticalAlignment.Center,
                    });

                    fields.Add(new Field
                    {
                        Name        = "NameTI",
                        DataType    = typeof(IFreeHierarchyObject),
                        Label       = "ТИ",
                        Width       = new FieldLength(200),
                        AllowFixing = AllowFieldFixing.Near,
                        //FixedLocation = FixedFieldLocation.FixedToNearEdge,
                        Settings =
                        {
                            AllowGroupBy              = true,
                            GroupByComparer           = comparer,
                            SortComparer              = comparer,
                            FilterComparer            = comparer,
                            CellVisibilityWhenGrouped = Visibility.Collapsed,
                            FilterOperandUIType       = FilterOperandUIType.DropDownList,
                            AllowFixing             = AllowFieldFixing.Near,
                            AllowEdit               = false,
                            EditorStyle             = null,
                            AllowRecordFiltering    = true,
                            CellValuePresenterStyle = hierObjectStyle,
                        },
                        HorizontalContentAlignment = HorizontalAlignment.Left,
                        VerticalContentAlignment   = VerticalAlignment.Center,
                    });

                    fields.Add(new TemplateField
                    {
                        Name            = "Channel",
                        Label           = "К",
                        DataType        = typeof(object),
                        DisplayTemplate = chTemplate,
                        Width           = new FieldLength(40),
                        AllowFixing     = AllowFieldFixing.Near,
                        //FixedLocation = FixedFieldLocation.FixedToNearEdge,
                        Settings =
                        {
                            AllowGroupBy         = true,
                            FilterOperandUIType  = FilterOperandUIType.DropDownList,
                            AllowFixing          = AllowFieldFixing.Near,
                            AllowEdit            = false,
                            EditorStyle          = null,
                            AllowRecordFiltering = true,
                        },
                    });

                    fieldLayout.Fields.Add(new Field
                    {
                        Name        = "DataSource",
                        Label       = "Источник данных",
                        Width       = new FieldLength(100),
                        AllowFixing = AllowFieldFixing.Near,
                        Settings    =
                        {
                            AllowGroupBy         = true,
                            FilterOperandUIType  = FilterOperandUIType.DropDownList,
                            AllowFixing          = AllowFieldFixing.Near,
                            AllowEdit            = false,
                            EditorStyle          = null,
                            AllowRecordFiltering = true,
                        },
                    });

                    fields.Add(new Field
                    {
                        Name        = "Coeff",
                        DataType    = typeof(double),
                        Width       = widthValue,
                        Label       = "Коэфф. тр.",
                        Format      = "#0",
                        AllowFixing = AllowFieldFixing.Near,
                        Settings    =
                        {
                            AllowGroupBy         = true,
                            AutoSizeOptions      = FieldAutoSizeOptions.None,
                            Width                = widthValue,
                            SummaryUIType        = SummaryUIType.MultiSelect,
                            AllowEdit            = false,
                            EditorStyle          = null,
                            FilterOperandUIType  = FilterOperandUIType.Combo,
                            AllowRecordFiltering = true,
                        },
                        HorizontalContentAlignment = HorizontalAlignment.Right,
                        VerticalContentAlignment   = VerticalAlignment.Center,
                    });

                    if (useLossesCoefficient)
                    {
                        fields.Add(new Field
                        {
                            Name        = "CoeffLosses",
                            DataType    = typeof(double),
                            Width       = widthValue,
                            Label       = "Коэфф. потерь",
                            Format      = "#0.###",
                            AllowFixing = AllowFieldFixing.Near,
                            Settings    =
                            {
                                AllowGroupBy         = true,
                                AutoSizeOptions      = FieldAutoSizeOptions.None,
                                Width                = widthValue,
                                SummaryUIType        = SummaryUIType.MultiSelect,
                                AllowEdit            = false,
                                EditorStyle          = null,
                                FilterOperandUIType  = FilterOperandUIType.Combo,
                                AllowRecordFiltering = true,
                            },
                            HorizontalContentAlignment = HorizontalAlignment.Right,
                            VerticalContentAlignment   = VerticalAlignment.Center,
                        });
                    }

                    #endregion

                    #region Посуточные колонки
                    var        counter    = 0;
                    FieldGroup fieldGroup = null;

                    foreach (var col in userTable.Columns.OfType <DataColumnEx>())
                    {
                        if (col == null)
                        {
                            continue;
                        }

                        if (counter == 0)
                        {
                            fieldGroup = new FieldGroup
                            {
                                Label = col.GroupName,
                            };

                            fieldLayout.FieldItems.Add(fieldGroup);
                        }

                        var fld = AddFValueField(col.ColumnName, col.DataType, widthValue, col.IsFValue ? fValueStyle : fValueNoFlagStyle, null);
                        fld.Label = col.Caption;

                        //if (!col.IsFValue)
                        //{
                        //    fld.Format = "##0.######";
                        //}

                        fieldGroup.Children.Add(fld);

                        if (++counter == 3)
                        {
                            counter = 0;
                        }
                    }

                    #endregion
                }
                finally
                {
                    fieldLayout.Fields.EndUpdate();
                }

                dataGrid.RecordsInViewChanged += ExpandFirstRecord;
            }
            finally
            {
                dataGrid.DataSource = view;
                dataGrid.EndInit();
            }

#if DEBUG
            sw.Stop();
            Console.WriteLine("ConfigureGridDailyIntegrals - > {0} млс", sw.ElapsedMilliseconds);
#endif
        }
Exemple #20
0
 private bool CanRemovePortfolio(XamDataGrid dataGrid)
 {
     return(dataGrid != null && dataGrid.ActiveRecord != null && dataGrid.ActiveRecord.IsDataRecord);
 }