public void PrepareSpreadsheet()
        {
            //Create item
            var dataItem = new TestData { Text = "str", FractionalNumber = 1.0 };

            //Create spreadsheet, populate Items collection and build columns
            _spreadsheet = Mock.Create<SpreadsheetView>(Behavior.CallOriginal);
            _spreadsheet.ItemsSource = new List<TestData> { dataItem };
            _spreadsheet.OnApplyTemplate();

            //Need one of the columns built
            var column = _spreadsheet.Columns.FirstOrDefault(x => x.PropertyName == "Text");
            if (column == null)
                Assert.Fail();

            //Create container but suppress cells creation
            var container = new SpreadsheetItemContainer(_spreadsheet);
            Mock.NonPublic.Arrange(container, "InitializeCellsWithValues").DoNothing();
            container.Item = ItemWrap.BuildNew(dataItem);

            //Avoid calling original SetValueBinding and SetEditorParams methods from cell's constructor
            Mock.NonPublic.Arrange(typeof(Cell), "SetValueBinding", container.Item);
            Mock.NonPublic.Arrange(typeof(Cell), "SetEditorParams");
            _cell = column.CreateCell(container) as Cell;

            //Mock behavior
            _cellInteractionBehaviorMock = Mock.Create<CellInteractionBehavior>(Behavior.CallOriginal);

            //Attach behavior to the new control and check that OnAttached method was called
            _contentControl = Mock.Create<CellControl>(Behavior.CallOriginal);
            _contentControl.Content = _cell;
            _contentControl.DataContext = _cell;
            _cellInteractionBehaviorMock.Attach(_contentControl);
            Mock.NonPublic.Assert(_cellInteractionBehaviorMock, "OnAttached", Occurs.Once());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SpreadsheetItemContainer"/> class.
 /// </summary>
 /// <param name="spreadsheetView">The spreadsheet view.</param>
 public SpreadsheetItemContainer(SpreadsheetView spreadsheetView)
 {
     IsTabStop = false;
     _owner = spreadsheetView;
     if (_owner != null)
         _topLevelSpreadsheet = _owner.GetTopLevelSpreadsheet();
     Cells = new CellCollection();
 }
        public void AssignItemsSourceFirstTest()
        {
            var spreadsheet = new SpreadsheetView();
            var spreadsheetData = new List<TestData>
            {
                new TestData{Text = "string1", FractionalNumber = 10.0},
                new TestData{Text = "string2", FractionalNumber = 20.0},
                new TestData{Text = "test text", FractionalNumber = 30.2}
            };

            var privateAccessor = new PrivateAccessor(spreadsheet);

            //By default ItemsSource of SpreadsheetView is null
            Assert.IsNull(spreadsheet.ItemsSource);

            Mock.NonPublic.Arrange<SpreadsheetView>("OnItemsSourceChanged", ArgExpr.IsAny<DependencyObject>(), ArgExpr.IsAny<DependencyPropertyChangedEventArgs>())
                          .CallOriginal()
                          .MustBeCalled();
            spreadsheet.ItemsSource = spreadsheetData;
            Assert.AreEqual(spreadsheet.ItemsSource, spreadsheetData);
            Mock.NonPublic.Assert<SpreadsheetView>("OnItemsSourceChanged", ArgExpr.IsAny<DependencyObject>(), ArgExpr.IsAny<DependencyPropertyChangedEventArgs>());

            //FillItemsSource must be called from OnApplyTemplate if it hasn't been invoked yet 
            Mock.NonPublic.Assert(spreadsheet, "FillItemsSource", Occurs.Never(), ArgExpr.IsAny<IEnumerable>());
            Assert.IsFalse((bool)privateAccessor.GetField("_templateApplied"));

            //We've set SpreadsheetView.ItemsSource but ItemsControl.ItemsSource is still null
            var itemsControl = spreadsheet as ItemsControl;
            Assert.IsNull(itemsControl.ItemsSource);

            //Invoke OnApplyTemplate manually
            spreadsheet.OnApplyTemplate();
            Mock.NonPublic.Assert(spreadsheet, "FillItemsSource", Occurs.Once(), ArgExpr.IsAny<IEnumerable>());
            Assert.IsTrue((bool)privateAccessor.GetField("_templateApplied"));

            //FillItemsSource calls PopulateColumns
            Mock.NonPublic.Assert(spreadsheet, "PopulateColumns", Occurs.Once(), ArgExpr.IsAny<SpreadsheetElementCollection>());

            //Now ItemsControl.ItemsSource has value as well
            Assert.IsNotNull(itemsControl.ItemsSource);
            Assert.AreEqual(itemsControl.ItemsSource.GetType(), typeof(SpreadsheetElementCollection));

            //SpreadsheetView.ItemsCollection has only getter which retrieves data from ItemsControl.ItemsSource and casts it to SpreadsheetElementCollection
            Assert.AreEqual(itemsControl.ItemsSource, spreadsheet.ItemsCollection);

            //Assure that all our elements are there
            Assert.AreEqual(((IList)spreadsheet.ItemsSource).Count, spreadsheetData.Count);
            Assert.AreEqual(((IList)itemsControl.ItemsSource).Count, spreadsheetData.Count);
        }
        public void AddNewItemsCommandTests()
        {
            // arrange
            var vm = new SpreadsheetColumnBase();

            var view = new SpreadsheetView();
            Mock.Arrange(() => view.KeyNavigationByDemand(Key.Insert, true)).MustBeCalled();
            Mock.Arrange(() => vm.Owner).Returns(view);

            // act
            vm.AddNewItemsCommand.Execute(null);

            // assert
            Mock.Assert(view);
        }
        public void AssignItemsSourceAfterTemplateAppliedTest()
        {
            var spreadsheet = new SpreadsheetView();
            var spreadsheetData = new List<TestData>
            {
                new TestData{Text = "string1", FractionalNumber = 10.0},
                new TestData{Text = "string2", FractionalNumber = 20.0},
                new TestData{Text = "test text", FractionalNumber = 30.2}
            };

            var privateAccessor = new PrivateAccessor(spreadsheet);

            //First we call OnApplyTemplate and only then set value to ItemsSource
            spreadsheet.OnApplyTemplate();
            //FillItemsSource can not be called if ItemsSource is null
            Mock.NonPublic.Assert(spreadsheet, "FillItemsSource", Occurs.Never(), ArgExpr.IsAny<IEnumerable>());
            Assert.IsTrue((bool)privateAccessor.GetField("_templateApplied"));

            //FillItemsSource is invoked from OnItemsSourceChanged
            Mock.NonPublic.Arrange(spreadsheet, "FillItemsSource", ArgExpr.IsAny<IEnumerable>()).MustBeCalled();
            spreadsheet.ItemsSource = spreadsheetData;            
            Mock.Assert(spreadsheet);
        }
        public void AlternateRowsMethodTest()
        {
            //Create spreadsheet and load data
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);
            var itemList = new List<TestData>
            {
                new TestData(),
                new TestData()     
            };
            spreadsheet.ItemsSource = itemList;
            spreadsheet.OnApplyTemplate();
            Mock.NonPublic.Arrange(typeof(SpreadsheetView), "PopulateCells", ArgExpr.IsAny<SpreadsheetItemContainer>(), ArgExpr.IsAny<IWrap>()).DoNothing();

            //Get item wrappers
            var item1 = spreadsheet.ItemsCollection[0];
            var item2 = spreadsheet.ItemsCollection[1];

            //Call ItemContainerGenerator overrides 
            Mock.NonPublic.Arrange(typeof(CellBase), "SetEditorParams").IgnoreInstance().DoNothing();
            spreadsheet.ItemContainerStyle = new Style(typeof(SpreadsheetItemContainer));
            var container1 = privateAccessor.CallMethod("GetContainerForItemOverride") as SpreadsheetItemContainer;            
            privateAccessor.CallMethod("PrepareContainerForItemOverride", container1, item1);
            var container2 = privateAccessor.CallMethod("GetContainerForItemOverride") as SpreadsheetItemContainer;            
            privateAccessor.CallMethod("PrepareContainerForItemOverride", container2, item2);

            //Mock SetIsAlternate method for all SpreadsheetItemContainer instances
            var containerMock = Mock.Create<SpreadsheetItemContainer>(Constructor.Mocked);
            Mock.Arrange(() => containerMock.SetIsAlternate()).IgnoreInstance();            

            //Make spreadsheet invisible
            Mock.Arrange(() => spreadsheet.IsVisible).Returns(false);
            Mock.Arrange(() => spreadsheet.Items).CallOriginal().OccursNever();
            spreadsheet.AlternateRows();
            Mock.Assert(spreadsheet);

            //Test AlternateRows method in normal conditions
            Mock.Arrange(() => spreadsheet.IsVisible).Returns(true);
            Mock.Arrange(() => spreadsheet.Items).CallOriginal().MustBeCalled();
            spreadsheet.AlternateRows();
            var containersDict = privateAccessor.GetField("_containersDict") as Dictionary<IWrap, SpreadsheetItemContainer>;
            Mock.Assert(() => containersDict[item1].SetIsAlternate(), Occurs.Once());
            Mock.Assert(() => containersDict[item2].SetIsAlternate(), Occurs.Once());
            Mock.Assert(spreadsheet);
        }
        /// <summary>
        /// Draws the vertical lines.
        /// </summary>
        /// <param name="cell">The cell.</param>
        /// <param name="topLevelSpreadSheet">The top level spread sheet.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        private static bool DrawVerticalLines(CellBase cell, SpreadsheetView topLevelSpreadSheet)
        {
            if ((topLevelSpreadSheet.GridLinesVisibility & GridLinesVisibility.Vertical) == GridLinesVisibility.Vertical)
            {
                var stackCell = cell as StackCell;
                if (cell != null && (cell.Owner.Columns.Last() != cell.Column || cell.Owner.ParentSpreadsheet != null) && ((!cell.HasNested || (stackCell != null && (stackCell.ChildSpreadsheet == null || !stackCell.ChildSpreadsheet.Items.Any())))))
                {
                    return true;
                }
            }

            return false;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SpreadsheetColumnBase"/> class.
 /// </summary>
 /// <param name="owner">The owner.</param>
 internal SpreadsheetColumnBase(SpreadsheetView owner) : this()
 {            
     SetOwner(owner);
 }
        public void GetContainerFromItemMethodTest()
        {
            //Mock spreadsheet
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);

            //Prepare data
            var item = ItemWrap.BuildNew(new TestData());
            var container = new SpreadsheetItemContainer(spreadsheet);
            var containerHash = container.GetHashCode();

            var containersDict = privateAccessor.GetField("_containersDict") as Dictionary<IWrap, SpreadsheetItemContainer>;
            containersDict.Add(item, container);

            //Call GetContainerFromItem and assert results
            var result = spreadsheet.GetContainerFromItem(item);
            Assert.AreEqual(result.GetHashCode(), containerHash);
        }
        public void OnItemsChangedItemReplaceTest()
        {
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);            

            //Create data
            var oldItem = ItemWrap.BuildNew(new TestData());
            var newItem = ItemWrap.BuildNew(new TestData());
            var oldContainer = new SpreadsheetItemContainer(spreadsheet);
            var newContainer = new SpreadsheetItemContainer(spreadsheet);

            //Prepare event arguments and container dictionary
            var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItem, oldItem, 0);
            var containerDict = privateAccessor.GetField("_containersDict") as Dictionary<IWrap, SpreadsheetItemContainer>;
            containerDict.Add(oldItem, oldContainer);

            //Arrange methods
            Mock.Arrange(() => spreadsheet.ItemContainerGenerator.ContainerFromItem(newItem)).Returns(newContainer);
            Mock.NonPublic.Arrange(spreadsheet, "BindContainerToItem", newContainer, newItem).CallOriginal();

            //Call OnItemsChanged and Assert results
            privateAccessor.CallMethod("OnItemsChanged", args);
            Assert.AreEqual(containerDict.Count, 1);
            Assert.AreEqual(containerDict.First().Key, newItem);
            Assert.AreEqual(containerDict[newItem], newContainer);
            Mock.NonPublic.Assert(spreadsheet, "BindContainerToItem", Occurs.Once(), newContainer, newItem);
            Assert.IsTrue(oldContainer.IsDisposed);
        }
        public void OnItemsChangedItemAddTest()
        {
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);

            //Initialize ItemCollection
            Mock.NonPublic.Arrange(spreadsheet, "OnItemsChanged", ArgExpr.IsAny<NotifyCollectionChangedEventArgs>()).DoNothing();
            spreadsheet.ItemsSource = new List<TestData>();
            spreadsheet.OnApplyTemplate();
            Assert.IsNotNull(spreadsheet.ItemsCollection);
            Mock.Reset();

            //Create data item and its wrapper
            var dataItem = new TestData {Text = "test", FractionalNumber = 3.5};
            var itemWrap = ItemWrap.BuildNew(dataItem);

            //Arrabge ManageExpandStates and BindContainerToItem
            Mock.Arrange(() => spreadsheet.ManageExpandStates(Arg.IsAny<IDetailColumn>()));
            Mock.NonPublic.Arrange(spreadsheet, "BindContainerToItem", ArgExpr.IsAny<SpreadsheetItemContainer>(), ArgExpr.IsAny<IWrap>());

            //Make spreadsheet disposed
            privateAccessor.SetField("_disposed", true);
            spreadsheet.ItemsCollection.Add(itemWrap);

            //Check ManageExpandStates and BindContainerToItem invocations when spreadsheet is disposed
            Assert.IsTrue((bool)privateAccessor.GetField("_disposed"));
            Mock.NonPublic.Assert(spreadsheet, "BindContainerToItem", Occurs.Never(), ArgExpr.IsAny<SpreadsheetItemContainer>(), ArgExpr.IsAny<IWrap>());
            Mock.Assert(() => spreadsheet.ManageExpandStates(Arg.IsAny<IDetailColumn>()), Occurs.Never());

            //Mock ItemContainerGenerator.ContainerFromItem method and add new item to ItemsCollection
            //this invokes OnItemsChanged
            privateAccessor.SetField("_disposed", false);
            var container = new SpreadsheetItemContainer(spreadsheet);
            Mock.Arrange(() => spreadsheet.ItemContainerGenerator.ContainerFromItem(Arg.IsAny<object>())).Returns(container);
            Mock.Arrange(() => spreadsheet.ParentColumn).Returns(Mock.Create<IDetailColumn>());
            spreadsheet.ItemsCollection.Add(itemWrap);

            //Check ManageExpandStates and BindContainerToItem invocations when spreadsheet is not disposed
            Assert.IsFalse((bool)privateAccessor.GetField("_disposed"));
            Mock.NonPublic.Assert(spreadsheet, "BindContainerToItem", Occurs.Once(), container, itemWrap);
            Mock.Assert(() => spreadsheet.ManageExpandStates(Arg.IsAny<IDetailColumn>()), Occurs.Once());
        }
Beispiel #12
0
        /// <summary>
        /// Unselects the specified cell.
        /// </summary>
        /// <param name="cell">The cell.</param>
        /// <param name="caller">The caller.</param>
        public void Unselect(CellBase cell, SpreadsheetView caller = null)
        {
            foreach (var child in _childSpreadsheets.Where(x => x.IsVisible))
            {
                if (child != caller)
                    child.Unselect(cell, caller);
            }

            foreach (var item in Items)
            {
                var container = GetContainerFromItem((IWrap) item);
                if (container != null)
                    container.Unselect(cell);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Moves the selection from deleted cell.
        /// </summary>
        /// <param name="spreadsheet">The spreadsheet.</param>
        /// <param name="column">The column.</param>
        /// <param name="itemIndex">Index of the item.</param>
        private void MoveSelectionFromDeletedCell(SpreadsheetView spreadsheet, IColumn column, int itemIndex)
        {
            if (spreadsheet == null)
                return;

            if (spreadsheet.Items.Count == 0)
            {
                if (spreadsheet.ParentCell != null)
                    spreadsheet.ParentCell.ProcessSelectionCommand(new NavigationInfo());
            }
            else
            {
                SpreadsheetItemContainer itemContainer;
                if (itemIndex < spreadsheet.Items.Count)
                    itemContainer = GetContainerFromItem(spreadsheet.Items[itemIndex] as IWrap);
                else
                    itemContainer = GetContainerFromItem(spreadsheet.Items.Last() as IWrap);

                if (itemContainer != null && column != null)
                {
                    itemContainer.SelectByColumn(column, new NavigationInfo { SelectParents = column.IsParent });
                }
            }
        }
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="isDisposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool isDisposing) 
        {
            if (isDisposing)
            {
                CellSelectionInspector.CellsSelectedChain.Remove(this);

                _columnPresenter = null;
                _owner = null;
                ParentColumn = null;

                PreviousColumn = null;

                ClearValue(ForegroundProperty);
                ClearValue(BackgroundProperty);
                ClearValue(StyleProperty);

                WidthChanged = null;
                PresenterChanged = null;
                PropertyChanged = null;
            }
            
            IsDisposed = true;
        }
        /// <summary>
        /// Sets the owner.
        /// </summary>
        /// <param name="owner">The owner.</param>
        /// <param name="forceSetOwner">if set to <c>true</c> [force set owner].</param>
        public void SetOwner(SpreadsheetView owner, bool forceSetOwner = false)
        {
            var oldOwner = _owner;

            if (_owner == null || _owner.IsDisposed || forceSetOwner)
            {
                _owner = owner;                
                OnPropertyChanged("Owner");

                if (owner != null)
                    ParentColumn = owner.ParentColumn as SpreadsheetColumnBase;
                
                SetInheritanceLevel();
                OnOwnerChanged(oldOwner, owner);
            }
            else
            {
                if (owner != null && ColumnPanelLoaded)
                    owner.ColumnPanelLoaded = true;
            }

            if(forceSetOwner && oldOwner != null)
                oldOwner.Dispose();            
        }
 /// <summary>
 /// Called when [owner changed].
 /// </summary>
 /// <param name="oldOwner">The old owner.</param>
 /// <param name="newOwner">The new owner.</param>
 protected void OnOwnerChanged(SpreadsheetView oldOwner, SpreadsheetView newOwner)
 {
     if (OwnerChanged != null)
         OwnerChanged(this, new ColumnOwnerChangedEventArgs(oldOwner, newOwner));
 }
        public void CheckPropertiesInitialValuesTest()
        {
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);

            Assert.IsNotNull(privateAccessor.GetField("_sharedColumns"));
            Assert.IsNotNull(privateAccessor.GetField("_containersDict"));
            Assert.IsFalse((bool)privateAccessor.GetField("_loaded"));
            Assert.IsFalse((bool)privateAccessor.GetField("_templateApplied"));

            Assert.IsFalse(spreadsheet.IsDisposed);
            Assert.IsFalse(spreadsheet.HasNested);
            Assert.IsTrue(spreadsheet.IsTopLevel);
            Assert.AreEqual(spreadsheet.FirstRowIndex, 1);
            Assert.IsFalse(spreadsheet.HasSelection);
            Assert.IsNull(spreadsheet.ParentColumn);
            Assert.IsNull(spreadsheet.GlobalDataContext);
            Assert.IsNotNull(spreadsheet.Columns);
            Assert.IsFalse(spreadsheet.Columns.Any());
            Assert.IsNull(spreadsheet.ItemsSource);
            Assert.IsTrue(spreadsheet.AutoGenerateColumns);
            Assert.IsNull(spreadsheet.ParentSpreadsheet);
            Assert.IsNull(spreadsheet.CustomDataContextInitializer);
            Assert.IsNull(spreadsheet.ParentCell);
            Assert.IsFalse(spreadsheet.IsNested);
            Assert.IsTrue(spreadsheet.IsVisible);
            Assert.IsNull(spreadsheet.ItemContainerStyle);
            Assert.IsTrue(spreadsheet.ShowColumnHeader);
            Assert.IsNull(spreadsheet.SelectedHeaderStyle);
            Assert.IsNull(spreadsheet.AlternateRowStyle);
            Assert.AreEqual(((SolidColorBrush)spreadsheet.AlternateRowBackground).Color, Colors.Yellow);
            Assert.AreEqual(spreadsheet.AlternateStyle, AlternateStyles.None);
            Assert.AreEqual(((SolidColorBrush)spreadsheet.ColumnHeaderBackground).Color, Color.FromArgb(0xFF, 0x25, 0xA0, 0xDC));
            Assert.AreEqual(((SolidColorBrush)spreadsheet.ColumnSelectionBackground).Color, Color.FromArgb(0xFF, 0x2F, 0xD3, 0xFF));
            Assert.AreEqual(spreadsheet.GridLinesVisibility, GridLinesVisibility.Both);
            Assert.AreEqual(spreadsheet.RowIndicatorVisibility, Visibility.Visible);
            Assert.IsNull(spreadsheet.SelectedRowIndicatorStyle);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SpreadsheetDetailColumn"/> class.
 /// </summary>
 /// <param name="owner">The owner.</param>
 public SpreadsheetDetailColumn(SpreadsheetView owner) : base(owner)
 {
     IsToggledManually = false;
 }
        public void KeyNavigationByDemandMethodTest()
        {
            var spreadsheet = new SpreadsheetView();

            //Move right
            Mock.Arrange(() => spreadsheet.MoveRight()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Right);
            Mock.Assert(() => spreadsheet.MoveRight());

            //Move left
            Mock.Arrange(() => spreadsheet.MoveLeft()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Left);
            Mock.Assert(() => spreadsheet.MoveLeft());

            //Move up
            Mock.Arrange(() => spreadsheet.MoveUp()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Up);
            Mock.Assert(() => spreadsheet.MoveUp());

            //Move Down
            Mock.Arrange(() => spreadsheet.MoveDown()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Down);
            Mock.Assert(() => spreadsheet.MoveDown());

            //Start Editing
            Mock.NonPublic.Arrange(spreadsheet, "StartEditing").DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Enter);
            Mock.NonPublic.Assert(spreadsheet, "StartEditing");

            //Insert multiple records (there are cells in edit mode)
            Mock.Arrange(() => Keyboard.Modifiers).Returns(ModifierKeys.Shift);
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[1]);
            Mock.Arrange(() => spreadsheet.InsertMultipleRecords()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Insert, true);
            Mock.Assert(() => spreadsheet.InsertMultipleRecords(), Occurs.Never());

            //Insert multiple records (there are no cells in edit mode)
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[0]);
            spreadsheet.KeyNavigationByDemand(Key.Insert, true);
            Mock.Assert(() => spreadsheet.InsertMultipleRecords(), Occurs.Once());

            //Insert new (there are cells in edit mode)
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[1]);
            Mock.Arrange(() => Keyboard.Modifiers).Returns(ModifierKeys.None);
            Mock.Arrange(() => spreadsheet.InsertRecord()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Insert);
            Mock.Assert(() => spreadsheet.InsertRecord(), Occurs.Never());

            //Insert new (there are no cells in edit mode)
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[0]);
            Mock.Arrange(() => Keyboard.Modifiers).Returns(ModifierKeys.None);
            Mock.Arrange(() => spreadsheet.InsertRecord()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Insert);
            Mock.Assert(() => spreadsheet.InsertRecord(), Occurs.Once());

            //Delete record (there are cells in edit mode)
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[1]);
            Mock.Arrange(() => Keyboard.Modifiers).Returns(ModifierKeys.Shift);
            Mock.Arrange(() => spreadsheet.DeleteRecord()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Delete, true);
            Mock.Assert(() => spreadsheet.DeleteRecord(), Occurs.Never());

            //Delete record (there are no cells in edit mode)
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[0]);
            Mock.Arrange(() => Keyboard.Modifiers).Returns(ModifierKeys.Shift);
            Mock.Arrange(() => spreadsheet.DeleteRecord()).DoNothing();
            spreadsheet.KeyNavigationByDemand(Key.Delete, true);
            Mock.Assert(() => spreadsheet.DeleteRecord(), Occurs.Once());

            //Delete values from selected cells (there are cells in edit mode)
            var cell1 = Mock.Create<Cell>(Constructor.Mocked);
            var cell2 = Mock.Create<StackCell>(Constructor.Mocked);
            Mock.Arrange(() => spreadsheet.GetSelectedCells()).Returns(new CellBase[] {cell1, cell2});
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[1]);
            Mock.Arrange(() => Keyboard.Modifiers).Returns(ModifierKeys.None);
            spreadsheet.KeyNavigationByDemand(Key.Delete);
            Mock.Assert(() => cell1.ClearValue(), Occurs.Never());
            Mock.Assert(() => cell2.ClearValue(), Occurs.Never());

            //Delete values from selected cells (there are no cells in edit mode)
            Mock.Arrange(() => spreadsheet.GetEditedCells()).Returns(new CellBase[0]);
            spreadsheet.KeyNavigationByDemand(Key.Delete);
            Mock.Assert(() => cell1.ClearValue(), Occurs.Once());
            Mock.Assert(() => cell2.ClearValue(), Occurs.Once());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ColumnOwnerChangedEventArgs"/> class.
 /// </summary>
 /// <param name="oldValue">The old value.</param>
 /// <param name="newValue">The new value.</param>
 public ColumnOwnerChangedEventArgs(SpreadsheetView oldValue, SpreadsheetView newValue)
 {
     OldValue = oldValue;
     NewValue = newValue;
 }
        public void OnItemsChangedItemRemoveTest()
        {
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);

            //Initialize ItemCollection
            Mock.NonPublic.Arrange(spreadsheet, "OnItemsChanged", ArgExpr.IsAny<NotifyCollectionChangedEventArgs>()).DoNothing();
            var list = new List<TestData>
            {
                new TestData {Text = "fff", FractionalNumber = 0},
                new TestData {Text = "item", FractionalNumber = 55},
                new TestData {Text = "last item", FractionalNumber = -5}
            };
            spreadsheet.ItemsSource = list;
            spreadsheet.OnApplyTemplate();
            Assert.IsNotNull(spreadsheet.ItemsCollection);
            Mock.Reset();

            var item1 = spreadsheet.ItemsCollection[0];
            var item2 = spreadsheet.ItemsCollection[1];
            var item3 = spreadsheet.ItemsCollection[2];

            //Bind item1 to container
            var container = new SpreadsheetItemContainer(spreadsheet);
            Mock.NonPublic.Arrange(container, "InitializeCellsWithValues");
            privateAccessor.CallMethod("BindContainerToItem", container, item1);
            privateAccessor.CallMethod("BindContainerToItem", container, item3);

            //Assert dictionary with containers
            var containerDict = privateAccessor.GetField("_containersDict") as Dictionary<IWrap, SpreadsheetItemContainer>;
            Assert.IsNotNull(containerDict);
            Assert.AreEqual(containerDict.Count, 2);
            containerDict.Add(item2, null);
            Assert.AreEqual(containerDict.Count, 3);

            //Remove second item from collection (when container is null)
            Mock.Arrange(() => containerDict.Remove(item2)).CallOriginal();
            spreadsheet.ItemsCollection.Remove(item2);
            Mock.Assert(() => containerDict.Remove(item2), Occurs.Once());
            Assert.AreEqual(containerDict.Count, 2);

            //Remove first item from collection (when container is disposed)
            Mock.Arrange(() => container.IsDisposed).Returns(true);
            spreadsheet.ItemsCollection.Remove(item1);            
            Mock.Assert(() => containerDict.Remove(item1), Occurs.Once());
            Assert.AreEqual(containerDict.Count, 1);

            //Remove item and dispose container            
            Mock.Arrange(() => container.IsDisposed).Returns(false);            
            spreadsheet.ItemsCollection.Remove(item3);
            Mock.Assert(() => containerDict.Remove(item3), Occurs.Exactly(2));
            Assert.AreEqual(containerDict.Count, 0);
            Mock.Reset();
            Assert.IsTrue(container.IsDisposed);
        }
        public void GetEditedCellsMethodTest()
        {
            //Mock spreadsheet
            var spreadsheetMock = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheetMock);

            //Load data            
            Mock.NonPublic.Arrange(typeof(CellBase), "SetEditorParams").IgnoreInstance().DoNothing();
            spreadsheetMock.ItemsSource = new List<TestData> { new TestData { Text = "text 1" }, new TestData { Text = "another text" } };
            spreadsheetMock.OnApplyTemplate();
            var item1 = spreadsheetMock.ItemsCollection[0];
            var item2 = spreadsheetMock.ItemsCollection[1];

            //Call ItemContainerGenerator overrides
            var container = privateAccessor.CallMethod("GetContainerForItemOverride") as SpreadsheetItemContainer;
            Assert.IsNotNull(container);
            spreadsheetMock.ItemContainerStyle = new Style(typeof(SpreadsheetItemContainer));
            privateAccessor.CallMethod("PrepareContainerForItemOverride", container, item1);
            privateAccessor.CallMethod("PrepareContainerForItemOverride", (SpreadsheetItemContainer)null, item2);

            //Assert _containersDict field
            var containersDict = privateAccessor.GetField("_containersDict") as Dictionary<IWrap, SpreadsheetItemContainer>;
            Assert.IsNotNull(containersDict);
            Assert.AreEqual(containersDict.Count, 2);
            Assert.IsTrue(containersDict.ContainsKey(item1));
            Assert.AreEqual(containersDict[item1], container);
            Assert.IsTrue(containersDict.ContainsKey(item2));
            Assert.IsNull(containersDict[item2]);

            //Assert cells
            Assert.IsNotNull(container.Cells);
            Assert.AreEqual(container.Cells.Count, 3);

            //Assert GetEditedCells call with only container from one of two elements and with no child spreadsheets
            var cell = container.Cells[1];
            Mock.Arrange(() => cell.IsEditMode).Returns(true);
            var editedCells = spreadsheetMock.GetEditedCells();
            Assert.AreEqual(editedCells.Count(), 1);
            Assert.AreEqual(editedCells[0], container.Cells[1]);

            //Add child spreadsheet
            var childSpreadsheet = new SpreadsheetView();
            var accessor = new PrivateAccessor(childSpreadsheet);
            childSpreadsheet.ItemsSource = new List<TestData> { new TestData { Text = "child item 1" }, new TestData { Text = "child item 2" } };
            childSpreadsheet.OnApplyTemplate();
            var item3 = childSpreadsheet.ItemsCollection[0];
            var item4 = childSpreadsheet.ItemsCollection[1];
            var childcontainer1 = accessor.CallMethod("GetContainerForItemOverride") as SpreadsheetItemContainer;
            var childcontainer2 = accessor.CallMethod("GetContainerForItemOverride") as SpreadsheetItemContainer;
            childSpreadsheet.ItemContainerStyle = new Style(typeof(SpreadsheetItemContainer));
            accessor.CallMethod("PrepareContainerForItemOverride", childcontainer1, item3);
            accessor.CallMethod("PrepareContainerForItemOverride", childcontainer2, item4);
            var cell2 = childcontainer1.Cells[1];
            Mock.Arrange(() => cell2.IsEditMode).Returns(true);
            var cell3 = childcontainer2.Cells[2];
            Mock.Arrange(() => cell3.IsEditMode).Returns(true);

            ((List<SpreadsheetView>)privateAccessor.GetField("_childSpreadsheets")).Add(childSpreadsheet);

            //Assert GetEditedCells call involving invisible child spreadsheet
            Mock.Arrange(() => childSpreadsheet.IsVisible).Returns(false);
            editedCells = spreadsheetMock.GetEditedCells();
            Assert.AreEqual(editedCells.Count(), 1);
            Assert.AreEqual(editedCells[0], container.Cells[1]);

            //Assert GetEditedCells call involving visible child spreadsheet
            Mock.Arrange(() => childSpreadsheet.IsVisible).Returns(true);
            editedCells = spreadsheetMock.GetEditedCells();
            Assert.AreEqual(editedCells.Count(), 3);
            Assert.AreEqual(editedCells[0], childcontainer1.Cells[1]);
            Assert.AreEqual(editedCells[1], childcontainer2.Cells[2]);
            Assert.AreEqual(editedCells[2], container.Cells[1]);
        }
        public void OnItemsChangedItemResetTest()
        {
            var spreadsheet = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheet);

            var container = new SpreadsheetItemContainer(spreadsheet);

            //Arrange ContainerFromItem and initialize spreadsheet ItemsSource collection
            Mock.Arrange(() => spreadsheet.ItemContainerGenerator.ContainerFromItem(Arg.IsAny<IWrap>())).Returns(container);
            spreadsheet.ItemsSource = new List<TestData> {new TestData{Text = "data1"}};
            spreadsheet.OnApplyTemplate();
            var containersDict = privateAccessor.GetField("_containersDict") as Dictionary<IWrap, SpreadsheetItemContainer>;
            Assert.AreEqual(containersDict.Count, 1);
            Assert.AreEqual(((TestData)containersDict.First().Key.Data).Text, "data1");

            //Re-initialize collection to call OnItemsChanged with Reset action and assert results
            Mock.NonPublic.Arrange(spreadsheet, "DisposeContainers").CallOriginal().MustBeCalled();
            spreadsheet.ItemsSource = new List<TestData> { new TestData { Text = "data2" } };
            Assert.AreEqual(containersDict.Count, 1);
            Assert.AreEqual(((TestData)containersDict.First().Key.Data).Text, "data2");            
            Mock.Assert(spreadsheet);
        }
        public void UnselectMethodTest()
        {
            var spreadsheetMock = new SpreadsheetView();
            var privateAccessor = new PrivateAccessor(spreadsheetMock);

            //Load data            
            Mock.NonPublic.Arrange(typeof(CellBase), "SetEditorParams").IgnoreInstance().DoNothing();
            spreadsheetMock.ItemsSource = new List<TestData> { new TestData { Text = "text 1" }, new TestData { Text = "another text" } };
            spreadsheetMock.OnApplyTemplate();
            var item1 = spreadsheetMock.ItemsCollection[0];
            var item2 = spreadsheetMock.ItemsCollection[1];

            //Call ItemContainerGenerator overrides
            var container = privateAccessor.CallMethod("GetContainerForItemOverride") as SpreadsheetItemContainer;
            Assert.IsNotNull(container);
            spreadsheetMock.ItemContainerStyle = new Style(typeof(SpreadsheetItemContainer));
            privateAccessor.CallMethod("PrepareContainerForItemOverride", container, item1);
            privateAccessor.CallMethod("PrepareContainerForItemOverride", (SpreadsheetItemContainer)null, item2);

            //Unselect cells from local spreadsheet
            Mock.Arrange(() => spreadsheetMock.Unselect(Arg.IsAny<CellBase>(), Arg.IsAny<SpreadsheetView>()));
            Mock.Arrange(() => container.Unselect(Arg.IsAny<CellBase>())).IgnoreInstance().OccursOnce();
            var cell = Mock.Create<CellBase>(Constructor.Mocked, Behavior.Loose);
            spreadsheetMock.Unselect(cell);
            Mock.Assert(container);

            //Create child spreadsheets
            var childSpreadsheet1 = Mock.Create<SpreadsheetView>(Constructor.Mocked, Behavior.Loose);
            Mock.Arrange(() => childSpreadsheet1.IsVisible).Returns(true);
            var childSpreadsheet2 = Mock.Create<SpreadsheetView>(Constructor.Mocked, Behavior.Loose);
            Mock.Arrange(() => childSpreadsheet2.IsVisible).Returns(false);
            var childSpreadsheet3 = Mock.Create<SpreadsheetView>(Constructor.Mocked, Behavior.Loose);
            Mock.Arrange(() => childSpreadsheet3.IsVisible).Returns(true);

            //Add child spreadsheets
            var childSpreadsheets = privateAccessor.GetField("_childSpreadsheets") as List<SpreadsheetView>;
            childSpreadsheets.Add(childSpreadsheet1);
            childSpreadsheets.Add(childSpreadsheet2);
            childSpreadsheets.Add(childSpreadsheet3);

            //Call method with child spreadsheets and with caller (the second argument)
            Mock.Arrange(() => spreadsheetMock.Unselect(Arg.IsAny<CellBase>(), Arg.IsAny<SpreadsheetView>())).CallOriginal();
            spreadsheetMock.Unselect(cell, childSpreadsheet1);
            Mock.Assert(() => childSpreadsheet1.Unselect(cell, Arg.IsAny<SpreadsheetView>()), Occurs.Never());
            Mock.Assert(() => childSpreadsheet2.Unselect(cell, Arg.IsAny<SpreadsheetView>()), Occurs.Never());
            Mock.Assert(() => childSpreadsheet3.Unselect(cell, Arg.IsAny<SpreadsheetView>()), Occurs.Once());

            //Call method with child spreadsheets
            Mock.Arrange(() => container.Unselect(Arg.IsAny<CellBase>())).IgnoreInstance().Occurs(2);
            spreadsheetMock.Unselect(cell);
            Mock.Assert(() => childSpreadsheet1.Unselect(cell, Arg.IsAny<SpreadsheetView>()), Occurs.Once());
            Mock.Assert(() => childSpreadsheet2.Unselect(cell, Arg.IsAny<SpreadsheetView>()), Occurs.Never());
            Mock.Assert(() => childSpreadsheet3.Unselect(cell, Arg.IsAny<SpreadsheetView>()), Occurs.Exactly(2));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SpreadsheetColumnBase" /> class.
 /// </summary>
 /// <param name="owner">The owner.</param>
 public SpreadsheetStackColumn(SpreadsheetView owner) : base(owner)
 {
     InitializeDefaultConstructor();
 }
Beispiel #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpreadsheetColumn"/> class.
 /// </summary>
 /// <param name="owner">The owner.</param>
 internal SpreadsheetColumn(SpreadsheetView owner) : base(owner)
 {
 }
        public void GetTopLevelSpreadsheetMethodTest()
        {
            //Return spreadsheet if spreadsheet.ParentSpreadsheet is null
            var spreadsheet = new SpreadsheetView();
            var topLevelSpreadsheet = spreadsheet.GetTopLevelSpreadsheet();
            Assert.AreEqual(topLevelSpreadsheet, spreadsheet);

            //Return parentSpreadsheet if spreadsheet.ParentSpreadsheet equals parentSpreadsheet
            var parentSpreadsheet = new SpreadsheetView();
            spreadsheet.ParentSpreadsheet = parentSpreadsheet;
            topLevelSpreadsheet = spreadsheet.GetTopLevelSpreadsheet();
            Assert.AreEqual(topLevelSpreadsheet, parentSpreadsheet);
        }
        /// <summary>
        /// Gets the attached behavior.
        /// </summary>
        /// <param name="gridview">The gridview.</param>
        /// <returns>SpreadsheetViewDragDropBehavior.</returns>
        private static SpreadsheetViewDragDropBehavior GetAttachedBehavior(SpreadsheetView gridview)
        {
            if (gridview == null) return null;
            if (!Instances.ContainsKey(gridview))
            {
                Instances[gridview] = new SpreadsheetViewDragDropBehavior {AssociatedObject = gridview};
            }

            return Instances[gridview];
        }
Beispiel #29
0
        public static void ArrangeColumns(SpreadsheetView spreadsheet)
        {
            if (spreadsheet == null)
                return;

            var columns = new List<IColumn>();

            Action<SpreadsheetColumnCollection, List<IColumn>> addColumns = null;
            addColumns = (collection, list) =>
            {
                if (collection == null)
                    return;

                foreach (var column in collection)
                {
                    var stackColumn = column as IStackColumn;
                    if (stackColumn != null)
                    //if (column.IsParent)
                        //if (stackColumn is IDetailColumn && stackColumn.SubColumns.Count == 0)
                        //    list.Add(stackColumn);
                        //else
                        {
                            var columnPresenter = column.ColumnPresenter as StackColumnHeader;
                            if (columnPresenter != null)
                            {
                                if (!columnPresenter.ShowSubColumns)
                                    list.Add(column);
                                else
                                    addColumns(stackColumn.SubColumns, list);
                            }
                            else
                                addColumns(stackColumn.SubColumns, list);
                        }
                    else
                        list.Add(column);
                }
            };

            addColumns(spreadsheet.Columns, columns);
            if (columns.Count == 0)
                return;

            foreach (IColumn column in columns)
            {
                if (column.ColumnPresenter != null)
                {
                    if (!column.WidthBeforeArrangement.HasValue)
                        column.WidthBeforeArrangement = column.ColumnPresenter.DesiredSize.Width;
                    else if (!double.IsNaN(column.Width))
                        column.WidthBeforeArrangement = ((column.WidthBeforeArrangement + column.Width) / 2);
                }
            }

            var columnPresenterList = columns.Where(x => x.ColumnPresenter != null).Select(x => x.ColumnPresenter).ToList();

            var spreadSheetWidth = spreadsheet.CalculateSpreadsheetWidth();

            var totalDesiredWidth = columnPresenterList.Sum(x =>
                                    {
                                        var sourceColumn = x.DataContext as IColumn;
                                        return sourceColumn != null && sourceColumn.WidthBeforeArrangement.HasValue
                                            ? Math.Min(sourceColumn.WidthBeforeArrangement.Value, x.DesiredSize.Width)
                                            : x.DesiredSize.Width;
                                    });
            var totalAvailableWidth = spreadSheetWidth;

            if (spreadsheet.ParentSpreadsheet == null)
            {
                var rowIndicatorColumns = columns.Where(x => x.IsRowIndicator);
                if (rowIndicatorColumns.Any())
                {
                    columnPresenterList.RemoveAll(x => ((IColumn)x.DataContext).IsRowIndicator);
                    var rowIndicatorColumnsWidth = rowIndicatorColumns.Sum(x => x.Width);
                    totalDesiredWidth = totalDesiredWidth - rowIndicatorColumnsWidth;
                    totalAvailableWidth = spreadSheetWidth - rowIndicatorColumnsWidth;
                }
            }

            if (totalDesiredWidth > totalAvailableWidth)
            {
                var midWidth = totalAvailableWidth / columnPresenterList.Count;

                var columnDict = new Dictionary<IColumn, WidthRestrictions>();
                foreach (var child in columnPresenterList)
                {
                    if (child.DataContext is IColumn)
                    {
                        var column = child.DataContext as IColumn;

                        var defaultRange = new WidthRestrictions(column.MinWidth, column.MaxWidth);
                        defaultRange.UpdateValue(column.WidthBeforeArrangement.HasValue 
                                                    ? Math.Min(column.WidthBeforeArrangement.Value, child.DesiredSize.Width) 
                                                    : child.DesiredSize.Width);

                        columnDict.Add(column, defaultRange);
                    }
                }

                var regularColumns = columnDict.Where(x => x.Value.DesiredWidth <= midWidth).ToList();
                var wideColumns = columnDict.Where(x => x.Value.DesiredWidth > midWidth).ToList();
                var totalMinWidth = columnDict.Select(x => x.Value.DesiredWidth > midWidth ? midWidth : x.Value.DesiredWidth).Sum();
                var availableWidthLeft = totalAvailableWidth - totalMinWidth;
                var wideColumnsTotalWidth = wideColumns.Sum(x => x.Value.DesiredWidth);

                if (availableWidthLeft < wideColumnsTotalWidth)
                {
                    var availableWidth80 = Math.Ceiling(availableWidthLeft * 0.8);
                    var availableWidth20 = Math.Ceiling(availableWidthLeft * 0.2);

                    foreach (var col in wideColumns.ToList())
                    {
                        var currentValue = columnDict[col.Key].DesiredWidth;   
                        var newPossibleValue = Math.Ceiling(midWidth + ((col.Value.DesiredWidth / wideColumnsTotalWidth) * availableWidth80));

                        if ((newPossibleValue < 150) && (currentValue > newPossibleValue * 2))
                            columnDict[col.Key].UpdateValue(newPossibleValue * 2);
                        else
                            columnDict[col.Key].UpdateValue(newPossibleValue);
                    }

                    var extraWidth = availableWidth20 / regularColumns.Count;
                    foreach (var col in regularColumns.ToList())
                    {
                        columnDict[col.Key].UpdateValue(columnDict[col.Key].DesiredWidth + extraWidth);
                    }
                }
                else if (availableWidthLeft > wideColumnsTotalWidth)
                {
                    var extraWidth = (availableWidthLeft - wideColumnsTotalWidth) / columnDict.Count;

                    foreach (var col in regularColumns.ToList())
                    {
                        columnDict[col.Key].UpdateValue(columnDict[col.Key].DesiredWidth + extraWidth);
                    }

                    foreach (var col in wideColumns.ToList())
                    {
                        columnDict[col.Key].UpdateValue(midWidth + ((col.Value.DesiredWidth / wideColumnsTotalWidth) * availableWidthLeft) + extraWidth);
                    }
                }

                foreach (var item in columnDict)
                {
                    if (item.Key.ColumnPanelLoaded)
                        item.Key.Width = Math.Ceiling(item.Value.DesiredWidth);//Math.Round(item.Value.DesiredWidth, 0);
                }

                foreach (var col in spreadsheet.Columns.Where(x => x.IsParent))
                {
                    col.UpdateAutoSize();
                }

                var roundingInaccuracy = spreadSheetWidth - columns.Sum(x => x.Width);
                if (wideColumns.Any() && roundingInaccuracy > 0)
                {
                    columnDict.FirstOrDefault(x => x.Key == wideColumns.First().Key).Key.Width += roundingInaccuracy;
                }
            }
            else
            {
                var extraSpace = (totalAvailableWidth - totalDesiredWidth) / columns.Count(x => !x.IsRowIndicator);
                foreach (var column in columns.Where(x => !x.IsRowIndicator))
                {
                    if (column.ColumnPanelLoaded && (double.IsNaN(column.Width) || column.WidthBeforeArrangement.HasValue))
                        column.Width = Math.Ceiling((column.WidthBeforeArrangement.HasValue
                                                        ? Math.Min(column.WidthBeforeArrangement.Value, column.ColumnPresenter.DesiredSize.Width)
                                                        : column.ColumnPresenter.DesiredSize.Width) + extraSpace);
                    else
                        column.Width += extraSpace;
                }
            }
        }
        /// <summary>
        /// Cleans up.
        /// </summary>
        protected virtual void CleanUp()
        {
            UnsubscribeFromDragDropEvents();

            if (Instances.ContainsKey(AssociatedObject))
            {
                var behavior = Instances[AssociatedObject];                
                Instances.Remove(AssociatedObject);
                behavior.AssociatedObject = null;
            }

            AssociatedObject = null;
        }