Example #1
0
        public void Can_use_Composite()
        {
            // Arrange
            var sut = new FakeSut();

            var rootStartingAt5 = new TestRoot<DummyItem>("Starting with IntProperty = 5", () => new DummyItem(5));

            rootStartingAt5.Add(new TestLeaf<DummyItem>(rootStartingAt5, new Mutation<DummyItem>("setting it to 4", d => { d.IntProperty = 4; })));
            rootStartingAt5.Add(new TestLeaf<DummyItem>(rootStartingAt5, new Mutation<DummyItem>("setting it to 3", d => { d.IntProperty = 3; })));

            var adding2 = new TestComposite<DummyItem>(rootStartingAt5, new Mutation<DummyItem>("adding 2", d => { d.IntProperty = d.IntProperty + 2; }));
            adding2.Add(new TestLeaf<DummyItem>(adding2, new Mutation<DummyItem>("removing 1", d => { d.IntProperty = d.IntProperty - 1; })));
            adding2.Add(new TestLeaf<DummyItem>(adding2, new Mutation<DummyItem>("removing 3", d => { d.IntProperty = d.IntProperty - 3; })));
            rootStartingAt5.Add(adding2);

            var adding3 = new TestComposite<DummyItem>(rootStartingAt5, new Mutation<DummyItem>( "adding 3", d => { d.IntProperty = d.IntProperty + 3; }));
            adding2.Add(new TestLeaf<DummyItem>(adding3, new Mutation<DummyItem>("removing 2", d => { d.IntProperty = d.IntProperty - 2; })));
            adding2.Add(new TestLeaf<DummyItem>(adding3, new Mutation<DummyItem>("removing 4", d => { d.IntProperty = d.IntProperty - 4; })));

            rootStartingAt5.Add(adding3);

            //Assert.AreEqual("", String.Join("\n", rootStartingAt5.Enumerate().ToList().Select(t => t.Description)));

            rootStartingAt5.Walk((start) =>
            {
                var initial = start.Arrange();
                var actual = sut.DoIt(initial);
                DummyAssert.AssertIsNotFive(actual, start.Description);
            });

            // Act

            // Assert
        }
        public void Should_Bind_To_Later_Added_Element()
        {
            TextBlock target;
            StackPanel stackPanel;

            var root = new TestRoot
            {
                Child = stackPanel = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (target = new TextBlock
                        {
                            Name = "target",
                        }),
                    }
                }
            };

            var binding = new Binding
            {
                ElementName = "source",
                Path = "Text",
            };

            binding.Bind(target, TextBlock.TextProperty);

            stackPanel.Children.Add(new TextBlock
            {
                Name = "source",
                Text = "foo",
            });

            Assert.Equal("foo", target.Text);
        }
Example #3
0
        public void Track_By_Name_Should_Find_Control_Added_Later()
        {
            StackPanel panel;
            TextBlock relativeTo;

            var root = new TestRoot
            {
                Child = (panel = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (relativeTo = new TextBlock
                        {
                            Name = "start"
                        }),
                    }
                })
            };

            var locator = ControlLocator.Track(relativeTo, "target");
            var target = new TextBlock { Name = "target" };
            var result = new List<IControl>();

            using (locator.Subscribe(x => result.Add(x)))
            {
                panel.Children.Add(target);
            }

            Assert.Equal(new[] { null, target }, result);
            Assert.Equal(0, root.NameScopeRegisteredSubscribers);
            Assert.Equal(0, root.NameScopeUnregisteredSubscribers);
        }
        public void Should_Bind_To_Element_Path()
        {
            TextBlock target;
            var root = new TestRoot
            {
                Child = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        new TextBlock
                        {
                            Name = "source",
                            Text = "foo",
                        },
                        (target = new TextBlock
                        {
                            Name = "target",
                        })
                    }
                }
            };

            var binding = new Binding
            {
                ElementName = "source",
                Path = "Text",
            };

            binding.Bind(target, TextBlock.TextProperty);

            Assert.Equal("foo", target.Text);
        }
        public void Should_Bind_To_Element()
        {
            TextBlock source;
            ContentControl target;

            var root = new TestRoot
            {
                Child = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (source = new TextBlock
                        {
                            Name = "source",
                            Text = "foo",
                        }),
                        (target = new ContentControl
                        {
                            Name = "target",
                        })
                    }
                }
            };

            var binding = new Binding
            {
                ElementName = "source",
            };

            binding.Bind(target, ContentControl.ContentProperty);

            Assert.Same(source, target.Content);
        }
Example #6
0
        public void Root_TreeContainerFromItem_Should_Return_Descendent_Item()
        {
            var tree = CreateTestTreeData();
            var target = new TreeView
            {
                Template = CreateTreeViewTemplate(),
                Items = tree,
                DataTemplates = CreateNodeDataTemplate(),
            };

            // For TreeViewItem to find its parent TreeView, OnAttachedToLogicalTree needs
            // to be called, which requires an IStyleRoot.
            var root = new TestRoot();
            root.Child = target;

            ApplyTemplates(target);

            var container = target.ItemContainerGenerator.Index.ContainerFromItem(
                tree[0].Children[1].Children[0]);

            Assert.NotNull(container);

            var header = ((TreeViewItem)container).Header;
            var headerContent = ((TextBlock)header).Text;

            Assert.Equal("Grandchild2a", headerContent);
        }
    public UIControlsDemo()
    {
      InitializeComponent();
      this.Closing += UIControlsDemo_Closing;

      MyRoot = TestRoot.NewEditableRoot();
      BindUI();
    }
Example #8
0
        public void Templated_Children_Should_Be_Styled()
        {
            var root = new TestRoot();
            var target = new ContentControl();
            var styler = new Mock<IStyler>();

            PerspexLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object);
            target.Content = "Foo";
            target.Template = GetTemplate();
            root.Child = target;

            target.ApplyTemplate();

            styler.Verify(x => x.ApplyStyles(It.IsAny<ContentControl>()), Times.Once());
            styler.Verify(x => x.ApplyStyles(It.IsAny<Border>()), Times.Once());
            styler.Verify(x => x.ApplyStyles(It.IsAny<ContentPresenter>()), Times.Once());
            styler.Verify(x => x.ApplyStyles(It.IsAny<TextBlock>()), Times.Once());
        }
        public void Control_Should_Unregister_With_NameScope()
        {
            var root = new TestRoot
            {
                Child = new Border
                {
                    Name = "foo",
                    Child = new Border
                    {
                        Name = "bar",
                    }
                }
            };

            root.Child = null;

            Assert.Null(root.FindControl<Border>("foo"));
            Assert.Null(root.FindControl<Border>("bar"));
        }
Example #10
0
        public void Controls_Should_Register_With_NameScope()
        {
            var root = new TestRoot
            {
                Child = new Border
                {
                    Name = "foo",
                    Child = new Border
                    {
                        Name = "bar",
                    }
                }
            };

            root.ApplyTemplate();

            Assert.Same(root.FindControl<Border>("foo"), root.Child);
            Assert.Same(root.FindControl<Border>("bar"), ((Border)root.Child).Child);
        }
Example #11
0
        public void Adding_To_Logical_Tree_Should_Reevaluate_DataTemplates()
        {
            var target = new ContentPresenter
            {
                Content = "Foo",
            };

            target.ApplyTemplate();
            Assert.IsType<TextBlock>(target.Child);

            var root = new TestRoot
            {
                DataTemplates = new DataTemplates
                {
                    new FuncDataTemplate<string>(x => new Decorator()),
                },
            };

            root.Child = target;
            target.ApplyTemplate();
            Assert.IsType<Decorator>(target.Child);
        }
        public void Should_Log_Binding_Error_When_Attached_To_Logical_Tree()
        {
            var target = new Decorator();
            var root   = new TestRoot {
                Child = target, DataContext = "foo"
            };
            var called = false;

            LogCallback checkLogMessage = (level, area, src, mt, pv) =>
            {
                if (level >= Avalonia.Logging.LogEventLevel.Warning)
                {
                    called = true;
                }
            };

            using (TestLogSink.Start(checkLogMessage))
            {
                target.Bind(Decorator.TagProperty, new Binding("Foo"));
            }

            Assert.True(called);
        }
        public void TransformToVisual_With_NonInvertible_RenderTransform_Should_Work()
        {
            var child = new Decorator
            {
                Width           = 100,
                Height          = 100,
                RenderTransform = new ScaleTransform()
                {
                    ScaleX = 0, ScaleY = 0
                }
            };
            var root = new TestRoot()
            {
                Child = child, Width = 400, Height = 400
            };

            root.Measure(Size.Infinity);
            root.Arrange(new Rect(new Point(), root.DesiredSize));

            var tr = root.TransformToVisual(child);

            Assert.Null(tr);
        }
Example #14
0
        public void CanSerializeCompound()
        {
            dynamic      test1     = new { Foo = "Foo", Bar = new[] { 1, 2, -3 }, Nested = new { Baz = "Quux", Nix = (string)null } };
            const string expected1 = @"{""Foo"":""Foo"",""Bar"":[1,2,-3],""Nested"":{""Baz"":""Quux"",""Nix"":null}}";

            Assert.Equal(expected1, Json.Serialize(test1));

            var test2 = new TestRoot
            {
                Foo = "foo",
                Sub = new TestSub
                {
                    Bar   = "bar",
                    Array = new[] { new TestPair {
                                        Key = "baz", Count = 42
                                    } }
                }
            };

            string expected2 = @"{'Foo':'foo','Sub':{'Bar':'bar','Array':[{'Key':'baz','Count':42}]}}".Replace('\'', '"');

            Assert.Equal(expected2, Json.Serialize(test2));
        }
        public void FindDescendantOfType_Finds_Nested_Child()
        {
            Button target;

            var root = new TestRoot
            {
                Child = new StackPanel
                {
                    Children =
                    {
                        new StackPanel
                        {
                            Children =
                            {
                                (target = new Button())
                            }
                        }
                    }
                }
            };

            Assert.Equal(target, root.FindDescendantOfType <Button>());
        }
        public void FindAncestorOfType_Finds_Ancestor_Of_Nested_Child()
        {
            Button target;

            var root = new TestRoot
            {
                Child = new StackPanel
                {
                    Children =
                    {
                        new StackPanel
                        {
                            Children =
                            {
                                (target = new Button())
                            }
                        }
                    }
                }
            };

            Assert.Equal(root, target.FindAncestorOfType <TestRoot>());
        }
Example #17
0
        public void Style_Should_Detach_Setters_When_Detach_Is_Called()
        {
            Border border;

            var style = new Style(x => x.OfType <Border>())
            {
                Setters = new[]
                {
                    new Setter(Border.BorderThicknessProperty, new Thickness(4)),
                }
            };

            var root = new TestRoot
            {
                Child = border = new Border(),
            };

            style.Attach(border, null);

            Assert.Equal(new Thickness(4), border.BorderThickness);
            style.Detach();
            Assert.Equal(new Thickness(0), border.BorderThickness);
        }
        public void Should_Be_Styled_As_UserControl()
        {
            using (UnitTestApplication.Start(TestServices.RealStyler))
            {
                var target = new UserControl();
                var root   = new TestRoot
                {
                    Styles =
                    {
                        new Style(x => x.OfType <UserControl>())
                        {
                            Setters =
                            {
                                new Setter(TemplatedControl.TemplateProperty, GetTemplate())
                            }
                        }
                    },
                    Child = target,
                };

                Assert.NotNull(target.Template);
            }
        }
Example #19
0
        public void Detaching_Then_Reattaching_To_Logical_Tree_Twice_Does_Not_Throw()
        {
            // # Issue 3487
            var target = new ItemsControl
            {
                Template     = GetTemplate(),
                Items        = new[] { "foo", "bar" },
                ItemTemplate = new FuncDataTemplate <string>((_, __) => new Canvas()),
            };

            var root = new TestRoot(target);

            root.Measure(Size.Infinity);
            root.Arrange(new Rect(root.DesiredSize));

            root.Child = null;
            root.Child = target;

            target.Measure(Size.Infinity);

            root.Child = null;
            root.Child = target;
        }
Example #20
0
        public void Style_Should_Detach_When_Control_Removed_From_Logical_Tree()
        {
            Border border;

            var style = new Style(x => x.OfType <Border>())
            {
                Setters =
                {
                    new Setter(Border.BorderThicknessProperty, new Thickness(4)),
                }
            };

            var root = new TestRoot
            {
                Child = border = new Border(),
            };

            style.TryAttach(border, null);

            Assert.Equal(new Thickness(4), border.BorderThickness);
            root.Child = null;
            Assert.Equal(new Thickness(0), border.BorderThickness);
        }
Example #21
0
        public void TemplateChild_DetachedFromLogicalTree_Should_Be_Raised()
        {
            Border templateChild = new Border();
            var    root          = new TestRoot
            {
                Child = new TestTemplatedControl
                {
                    Template = new FuncControlTemplate(_ => new Decorator
                    {
                        Child = templateChild,
                    })
                }
            };

            root.Child.ApplyTemplate();

            var raised = false;

            templateChild.DetachedFromLogicalTree += (s, e) => raised = true;

            root.Child = null;
            Assert.True(raised);
        }
        public void Should_Push_Opacity_For_Controls_With_Less_Than_1_Opacity()
        {
            using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
            {
                var root = new TestRoot
                {
                    Width = 100, Height = 100, Child = new Border {
                        Background = Brushes.Red, Opacity = 0.5,
                    }
                };

                root.Measure(Size.Infinity);
                root.Arrange(new Rect(root.DesiredSize));

                var target    = CreateTargetAndRunFrame(root);
                var context   = GetLayerContext(target, root);
                var animation = new BehaviorSubject <double>(0.5);

                context.Verify(x => x.PushOpacity(0.5), Times.Once);
                context.Verify(x => x.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100), default), Times.Once);
                context.Verify(x => x.PopOpacity(), Times.Once);
            }
        }
Example #23
0
        public void TreeViewItems_Level_Should_Be_Set_For_Derived_TreeView()
        {
            var tree   = CreateTestTreeData();
            var target = new DerivedTreeView
            {
                Template = CreateTreeViewTemplate(),
                Items    = tree,
            };

            var visualRoot = new TestRoot();

            visualRoot.Child = target;

            CreateNodeDataTemplate(target);
            ApplyTemplates(target);
            ExpandAll(target);

            Assert.Equal(0, GetItem(target, 0).Level);
            Assert.Equal(1, GetItem(target, 0, 0).Level);
            Assert.Equal(1, GetItem(target, 0, 1).Level);
            Assert.Equal(1, GetItem(target, 0, 2).Level);
            Assert.Equal(2, GetItem(target, 0, 1, 0).Level);
        }
Example #24
0
        public void Right_Click_On_UnselectedItem_Should_Clear_Existing_Selection()
        {
            using (Application())
            {
                var tree   = CreateTestTreeData();
                var target = new TreeView
                {
                    Template      = CreateTreeViewTemplate(),
                    Items         = tree,
                    SelectionMode = SelectionMode.Multiple,
                };

                var visualRoot = new TestRoot();
                visualRoot.Child = target;

                CreateNodeDataTemplate(target);
                ApplyTemplates(target);
                target.ExpandSubTree((TreeViewItem)target.Presenter.Panel.Children[0]);

                var rootNode = tree[0];
                var to       = rootNode.Children[0];
                var then     = rootNode.Children[1];

                var fromContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(rootNode);
                var toContainer   = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(to);
                var thenContainer = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(then);

                ClickContainer(fromContainer, KeyModifiers.None);
                ClickContainer(toContainer, KeyModifiers.Shift);

                Assert.Equal(2, target.SelectedItems.Count);

                _mouse.Click(thenContainer, MouseButton.Right);

                Assert.Equal(1, target.SelectedItems.Count);
            }
        }
Example #25
0
        public void Should_Set_Child_LogicalParent_After_Removing_And_Adding_Back_To_Logical_Tree()
        {
            using (UnitTestApplication.Start(TestServices.RealStyler))
            {
                var target = new ContentControl();
                var root   = new TestRoot
                {
                    Styles =
                    {
                        new Style(x => x.OfType <ContentControl>())
                        {
                            Setters =
                            {
                                new Setter(ContentControl.TemplateProperty, GetTemplate()),
                            }
                        }
                    },
                    Child = target
                };

                target.Content = "Foo";
                target.ApplyTemplate();
                target.Presenter.ApplyTemplate();

                Assert.Equal(target, target.Presenter.Child.LogicalParent);

                root.Child = null;

                Assert.Null(target.Template);

                target.Content = null;
                root.Child     = target;
                target.Content = "Bar";

                Assert.Equal(target, target.Presenter.Child.LogicalParent);
            }
        }
        public void GeometryClip_Should_Affect_Child_Layers()
        {
            using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
            {
                var       clip = StreamGeometry.Parse("M100,0 L0,100 100,100");
                Decorator decorator;
                Border    border;
                var       tree = new TestRoot
                {
                    Child = decorator = new Decorator
                    {
                        Clip   = clip,
                        Margin = new Thickness(12, 16),
                        Child  = border = new Border
                        {
                            Opacity = 0.5,
                            Child   = new Canvas(),
                        }
                    }
                };

                var layout = tree.LayoutManager;
                layout.ExecuteInitialLayoutPass();

                var animation = new BehaviorSubject <double>(0.5);
                border.Bind(Border.OpacityProperty, animation, BindingPriority.Animation);

                var scene        = new Scene(tree);
                var sceneBuilder = new SceneBuilder();
                sceneBuilder.UpdateAll(scene);

                var borderLayer = scene.Layers[border];
                Assert.Equal(
                    Matrix.CreateTranslation(12, 16),
                    ((MockStreamGeometryImpl)borderLayer.GeometryClip).Transform);
            }
        }
Example #27
0
        public void AutoScrollToSelectedItem_On_Reset_Works()
        {
            // Issue #3148
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                var items = new ResettingCollection(100);

                var target = new ListBox
                {
                    Items        = items,
                    ItemTemplate = new FuncDataTemplate <string>((x, _) =>
                                                                 new TextBlock
                    {
                        Text   = x,
                        Width  = 100,
                        Height = 10
                    }),
                    AutoScrollToSelectedItem = true,
                    VirtualizationMode       = ItemVirtualizationMode.Simple,
                };

                var root = new TestRoot(true, target);
                root.Measure(new Size(100, 100));
                root.Arrange(new Rect(0, 0, 100, 100));

                Assert.True(target.Presenter.Panel.Children.Count > 0);
                Assert.True(target.Presenter.Panel.Children.Count < 100);

                target.SelectedItem = "Item99";

                // #3148 triggered here.
                items.Reset(new[] { "Item99" });

                Assert.Equal(0, target.SelectedIndex);
                Assert.Equal(1, target.Presenter.Panel.Children.Count);
            }
        }
Example #28
0
        public void Should_Respect_Margin_For_ClipBounds()
        {
            using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
            {
                Canvas canvas;
                var    tree = new TestRoot
                {
                    Width  = 200,
                    Height = 300,
                    Child  = new Border
                    {
                        Margin = new Thickness(10, 20, 30, 40),
                        Child  = canvas = new Canvas
                        {
                            Background = Brushes.AliceBlue,
                        }
                    }
                };

                tree.Measure(Size.Infinity);
                tree.Arrange(new Rect(tree.DesiredSize));

                var result       = new Scene(tree);
                var sceneBuilder = new SceneBuilder();
                sceneBuilder.UpdateAll(result);

                var canvasNode = result.FindNode(canvas);
                Assert.Equal(new Rect(10, 20, 160, 240), canvasNode.ClipBounds);

                // Initial ClipBounds are correct, make sure they're still correct after updating canvas.
                result = result.Clone();
                Assert.True(sceneBuilder.Update(result, canvas));

                canvasNode = result.FindNode(canvas);
                Assert.Equal(new Rect(10, 20, 160, 240), canvasNode.ClipBounds);
            }
        }
Example #29
0
        public void Inactive_Values_Should_Not_Be_Made_Active_During_Style_Detach()
        {
            using var app = UnitTestApplication.Start(TestServices.RealStyler);

            var root = new TestRoot
            {
                Styles =
                {
                    new Style(x => x.OfType <Class1>())
                    {
                        Setters =
                        {
                            new Setter(Class1.FooProperty, "Foo"),
                        },
                    },

                    new Style(x => x.OfType <Class1>())
                    {
                        Setters =
                        {
                            new Setter(Class1.FooProperty, "Bar"),
                        },
                    }
                }
            };

            var target = new Class1();

            root.Child = target;

            var values = new List <string>();

            target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x));
            root.Child = null;

            Assert.Equal(new[] { "Bar", "foodefault" }, values);
        }
Example #30
0
        public void GetVisualsAt_Should_Respect_Geometry_Clip()
        {
            using (TestApplication())
            {
                Border border;
                Canvas canvas;
                var    container = new TestRoot
                {
                    Width  = 400,
                    Height = 400,
                    Child  = border = new Border
                    {
                        Background = Brushes.Red,
                        Clip       = StreamGeometry.Parse("M100,0 L0,100 100,100"),
                        Width      = 200,
                        Height     = 200,
                        Child      = canvas = new Canvas
                        {
                            Background = Brushes.Yellow,
                            Margin     = new Thickness(10),
                        }
                    }
                };

                container.Measure(Size.Infinity);
                container.Arrange(new Rect(container.DesiredSize));
                Assert.Equal(new Rect(100, 100, 200, 200), border.Bounds);

                var context = new DrawingContext(Mock.Of <IDrawingContextImpl>());

                var result = container.GetVisualsAt(new Point(200, 200));
                Assert.Equal(new IVisual[] { canvas, border }, result);

                result = container.GetVisualsAt(new Point(110, 110));
                Assert.Empty(result);
            }
        }
Example #31
0
        public async void Track_By_Name_Should_Find_Control_Added_Earlier()
        {
            TextBlock target;
            TextBlock relativeTo;

            var root = new TestRoot
            {
                Child = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (target = new TextBlock { Name = "target" }),
                        (relativeTo = new TextBlock { Name = "start" }),
                    }
                }
            };
            
            var locator = ControlLocator.Track(relativeTo, "target");
            var result = await locator.Take(1);

            Assert.Same(target, result);
            Assert.Equal(0, root.NameScopeRegisteredSubscribers);
            Assert.Equal(0, root.NameScopeUnregisteredSubscribers);
        }
Example #32
0
        public void DetachedFromLogicalParent_Should_Be_Called_When_Removed_From_Tree()
        {
            var root             = new TestRoot();
            var parent           = new Border();
            var child            = new Border();
            var grandchild       = new Border();
            var parentRaised     = false;
            var childRaised      = false;
            var grandchildRaised = false;

            parent.Child = child;
            child.Child  = grandchild;
            root.Child   = parent;

            parent.DetachedFromLogicalTree     += (s, e) => parentRaised = true;
            child.DetachedFromLogicalTree      += (s, e) => childRaised = true;
            grandchild.DetachedFromLogicalTree += (s, e) => grandchildRaised = true;

            root.Child = null;

            Assert.True(parentRaised);
            Assert.True(childRaised);
            Assert.True(grandchildRaised);
        }
Example #33
0
        public void CopySuffix()
        {
            var root = new TestRoot
            {
                new TestDirectory("dir")
                {
                    new TestFile("file"),
                    new TestFile("executable")
                    {
                        IsExecutable = true
                    },
                    new TestSymlink("symlink", "target")
                }
            };

            root.Build(SourceDirectory);

            new CloneDirectory(SourceDirectory, TargetDirectory)
            {
                TargetSuffix = "suffix"
            }.Run();

            root.Verify(Path.Combine(TargetDirectory, "suffix"));
        }
Example #34
0
        public void Setting_SelectedItem_Should_Set_Container_Selected()
        {
            var tree   = CreateTestTreeData();
            var target = new TreeView
            {
                Template      = CreateTreeViewTemplate(),
                Items         = tree,
                DataTemplates = CreateNodeDataTemplate(),
            };

            var visualRoot = new TestRoot();

            visualRoot.Child = target;
            ApplyTemplates(target);

            var item      = tree[0].Children[1].Children[0];
            var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);

            Assert.NotNull(container);

            target.SelectedItem = item;

            Assert.True(container.IsSelected);
        }
Example #35
0
        public void Should_Bind_To_Element()
        {
            TextBlock      source;
            ContentControl target;

            var root = new TestRoot
            {
                Child = new StackPanel
                {
                    Children =
                    {
                        (source  = new TextBlock
                        {
                            Name = "source",
                            Text = "foo",
                        }),
                        (target  = new ContentControl
                        {
                            Name = "target",
                        })
                    }
                }
            };

            root.RegisterChildrenNames();

            var binding = new Binding
            {
                ElementName = "source",
                NameScope   = new WeakReference <INameScope>(NameScope.GetNameScope(root))
            };

            target.Bind(ContentControl.ContentProperty, binding);

            Assert.Same(source, target.Content);
        }
Example #36
0
        public void MenuItem_Is_Enabled_When_Added_To_Logical_Tree_And_Bound_Command_Is_Added()
        {
            var viewModel = new
            {
                Command = new TestCommand(true),
            };

            var target = new MenuItem
            {
                DataContext = new object(),
                [!MenuItem.CommandProperty] = new Binding("Command"),
            };
            var root = new TestRoot {
                Child = target
            };

            Assert.True(target.IsEnabled);
            Assert.False(target.IsEffectivelyEnabled);

            target.DataContext = viewModel;

            Assert.True(target.IsEnabled);
            Assert.True(target.IsEffectivelyEnabled);
        }
Example #37
0
        public void Track_By_Name_Should_Track_Removal_And_Readd()
        {
            StackPanel panel;
            TextBlock  target;
            TextBlock  relativeTo;

            var root = new TestRoot
            {
                Child = panel = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (target = new TextBlock {
                            Name = "target"
                        }),
                        (relativeTo = new TextBlock {
                            Name = "start"
                        }),
                    }
                }
            };

            var locator = ControlLocator.Track(relativeTo, "target");
            var result  = new List <IControl>();

            locator.Subscribe(x => result.Add(x));

            var other = new TextBlock {
                Name = "target"
            };

            panel.Children.Remove(target);
            panel.Children.Add(other);

            Assert.Equal(new[] { target, null, other }, result);
        }
Example #38
0
        public void Should_Push_Opacity_Mask()
        {
            var root = new TestRoot
            {
                Width  = 100,
                Height = 100,
                Child  = new Border
                {
                    Background  = Brushes.Red,
                    OpacityMask = Brushes.Green,
                }
            };

            root.Measure(Size.Infinity);
            root.Arrange(new Rect(root.DesiredSize));

            var target    = CreateTargetAndRunFrame(root);
            var context   = GetLayerContext(target, root);
            var animation = new BehaviorSubject <double>(0.5);

            context.Verify(x => x.PushOpacityMask(Brushes.Green, new Rect(0, 0, 100, 100)), Times.Once);
            context.Verify(x => x.FillRectangle(Brushes.Red, new Rect(0, 0, 100, 100), 0), Times.Once);
            context.Verify(x => x.PopOpacityMask(), Times.Once);
        }
Example #39
0
        public void Adding_Tree_To_IStyleRoot_Should_Style_Controls()
        {
            using (AvaloniaLocator.EnterScope())
            {
                var root       = new TestRoot();
                var parent     = new Border();
                var child      = new Border();
                var grandchild = new Control();
                var styler     = new Mock <IStyler>();

                AvaloniaLocator.CurrentMutable.Bind <IStyler>().ToConstant(styler.Object);

                parent.Child = child;
                child.Child  = grandchild;

                styler.Verify(x => x.ApplyStyles(It.IsAny <IStyleable>()), Times.Never());

                root.Child = parent;

                styler.Verify(x => x.ApplyStyles(parent), Times.Once());
                styler.Verify(x => x.ApplyStyles(child), Times.Once());
                styler.Verify(x => x.ApplyStyles(grandchild), Times.Once());
            }
        }
        public void HitTest_Should_Not_Find_Invisible_Controls_At_Point()
        {
            using (TestApplication())
            {
                Border visible;
                var    root = new TestRoot
                {
                    Width  = 200,
                    Height = 200,
                    Child  = new Border
                    {
                        Width               = 100,
                        Height              = 100,
                        Background          = Brushes.Red,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment   = VerticalAlignment.Center,
                        IsVisible           = false,
                        Child               = visible = new Border
                        {
                            Background          = Brushes.Red,
                            HorizontalAlignment = HorizontalAlignment.Stretch,
                            VerticalAlignment   = VerticalAlignment.Stretch,
                        }
                    }
                };

                root.Renderer = new ImmediateRenderer(root);
                root.Measure(Size.Infinity);
                root.Arrange(new Rect(root.DesiredSize));
                root.Renderer.Paint(new Rect(root.ClientSize));

                var result = root.Renderer.HitTest(new Point(100, 100), root, null);

                Assert.Equal(new[] { root }, result);
            }
        }
Example #41
0
        public void Transition_Is_Not_Applied_To_Initial_Style()
        {
            using (UnitTestApplication.Start(TestServices.RealStyler))
            {
                var target  = CreateTarget();
                var control = new Control
                {
                    Transitions = { target.Object },
                };

                var root = new TestRoot
                {
                    Styles =
                    {
                        new Style(x => x.OfType <Control>())
                        {
                            Setters =
                            {
                                new Setter(Visual.OpacityProperty, 0.8),
                            }
                        }
                    }
                };

                root.Child = control;

                Assert.Equal(0.8, control.Opacity);

                target.Verify(x => x.Apply(
                                  It.IsAny <Control>(),
                                  It.IsAny <IClock>(),
                                  It.IsAny <object>(),
                                  It.IsAny <object>()),
                              Times.Never);
            }
        }
        public void Re_adding_To_Same_LogicalTree_Should_Not_Recreate_Template()
        {
            using (UnitTestApplication.Start(TestServices.RealStyler))
            {
                TestTemplatedControl target;
                var root = new TestRoot
                {
                    Styles = new Styles
                    {
                        new Style(x => x.OfType <TestTemplatedControl>())
                        {
                            Setters = new[]
                            {
                                new Setter(
                                    TemplatedControl.TemplateProperty,
                                    new FuncControlTemplate(_ => new Decorator
                                {
                                    Child = new Border(),
                                }))
                            }
                        }
                    },
                    Child = target = new TestTemplatedControl()
                };

                Assert.NotNull(target.Template);
                target.ApplyTemplate();
                var expected = (Decorator)target.GetVisualChildren().Single();

                root.Child = null;
                root.Child = target;
                target.ApplyTemplate();

                Assert.Same(expected, target.GetVisualChildren().Single());
            }
        }
        public void Templated_Children_Should_Be_Styled()
        {
            using (PerspexLocator.EnterScope())
            {
                var styler = new Mock<IStyler>();

                PerspexLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object);

                TestTemplatedControl target;

                var root = new TestRoot
                {
                    Child = target = new TestTemplatedControl
                    {
                        Template = new FuncControlTemplate(_ =>
                        {
                            return new StackPanel
                            {
                                Children = new Controls
                                {
                                    new TextBlock
                                    {
                                    }
                                }
                            };
                        }),
                    }
                };

                target.ApplyTemplate();

                styler.Verify(x => x.ApplyStyles(It.IsAny<TestTemplatedControl>()), Times.Once());
                styler.Verify(x => x.ApplyStyles(It.IsAny<StackPanel>()), Times.Once());
                styler.Verify(x => x.ApplyStyles(It.IsAny<TextBlock>()), Times.Once());
            }
        }
Example #44
0
        public void Setting_SelectedItem_Should_Set_Container_Selected()
        {
            var tree = CreateTestTreeData();
            var target = new TreeView
            {
                Template = CreateTreeViewTemplate(),
                Items = tree,
                DataTemplates = CreateNodeDataTemplate(),
            };

            var visualRoot = new TestRoot();
            visualRoot.Child = target;
            ApplyTemplates(target);

            var item = tree[0].Children[1].Children[0];
            var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);

            Assert.NotNull(container);

            target.SelectedItem = item;

            Assert.True(container.IsSelected);
        }
Example #45
0
        public void Removing_Item_Should_Remove_Itself_And_Children_From_Index()
        {
            var tree = CreateTestTreeData();
            var target = new TreeView
            {
                Template = CreateTreeViewTemplate(),
                DataTemplates = CreateNodeDataTemplate(),
                Items = tree,
            };

            var root = new TestRoot();
            root.Child = target;
            ApplyTemplates(target);

            Assert.Equal(4, target.ItemContainerGenerator.Index.Items.Count());

            tree[0].Children.RemoveAt(1);

            Assert.Equal(2, target.ItemContainerGenerator.Index.Items.Count());
        }
Example #46
0
        public void TabItem_Templates_Should_Be_Set_Before_TabItem_ApplyTemplate()
        {
            var collection = new[]
            {
                new TabItem
                {
                    Name = "first",
                    Content = "foo",
                },
                new TabItem
                {
                    Name = "second",
                    Content = "bar",
                },
                new TabItem
                {
                    Name = "3rd",
                    Content = "barf",
                },
            };

            var template = new FuncControlTemplate<TabItem>(x => new Decorator());

            using (UnitTestApplication.Start(TestServices.RealStyler))
            {
                var root = new TestRoot
                {
                    Styles = new Styles
                    {
                        new Style(x => x.OfType<TabItem>())
                        {
                            Setters = new[]
                            {
                                new Setter(TemplatedControl.TemplateProperty, template)
                            }
                        }
                    },
                    Child = new TabControl
                    {
                        Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate),
                        Items = collection,
                    }
                };
            }

            Assert.Same(collection[0].Template, template);
            Assert.Same(collection[1].Template, template);
            Assert.Same(collection[2].Template, template);
        }
Example #47
0
 public void Setup()
 {
   Root = new TestRoot();
   var rule = new OnlyForUS(AuthorizationActions.WriteProperty, TestRoot.NameProperty, TestRoot.CountryProperty);
   InitializeTest(rule, Root, typeof(TestRoot));
 }
Example #48
0
        public void Style_Should_Detach_When_Removed_From_Logical_Tree()
        {
            Border border;

            var style = new Style(x => x.OfType<Border>())
            {
                Setters = new[]
                {
                    new Setter(Border.BorderThicknessProperty, 4),
                }
            };

            var root = new TestRoot
            {
                Child = border = new Border(),
            };

            style.Attach(border, null);

            Assert.Equal(4, border.BorderThickness);
            root.Child = null;
            Assert.Equal(0, border.BorderThickness);
        }
Example #49
0
        public void Track_By_Name_Should_Find_Control_When_Tree_Changed()
        {
            TextBlock target1;
            TextBlock target2;
            TextBlock relativeTo;

            var root1 = new TestRoot
            {
                Child = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (relativeTo = new TextBlock
                        {
                            Name = "start"
                        }),
                        (target1 = new TextBlock { Name = "target" }),
                    }
                }
            };

            var root2 = new TestRoot
            {
                Child = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (target2 = new TextBlock { Name = "target" }),
                    }
                }
            };

            var locator = ControlLocator.Track(relativeTo, "target");
            var target = new TextBlock { Name = "target" };
            var result = new List<IControl>();

            using (locator.Subscribe(x => result.Add(x)))
            {
                ((StackPanel)root1.Child).Children.Remove(relativeTo);
                ((StackPanel)root2.Child).Children.Add(relativeTo);
            }

            Assert.Equal(new[] { target1, null, target2 }, result);
            Assert.Equal(0, root1.NameScopeRegisteredSubscribers);
            Assert.Equal(0, root1.NameScopeUnregisteredSubscribers);
        }
        public void Should_Bind_To_Later_Added_Element()
        {
            ContentControl target;
            StackPanel stackPanel;

            var root = new TestRoot
            {
                Child = stackPanel = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (target = new ContentControl
                        {
                            Name = "target",
                        }),
                    }
                }
            };

            var binding = new Binding
            {
                ElementName = "source",
            };

            binding.Bind(target, ContentControl.ContentProperty);

            var source = new TextBlock
            {
                Name = "source",
                Text = "foo",
            };

            stackPanel.Children.Add(source);

            Assert.Same(source, target.Content);
        }
Example #51
0
        public void Horizontal_Stays_Within_Constraints()
        {
            var cursorFactoryImpl = new Mock<IStandardCursorFactory>();
            PerspexLocator.CurrentMutable.Bind<IStandardCursorFactory>().ToConstant(cursorFactoryImpl.Object);

            var control1 = new Border { [Grid.RowProperty] = 0 };
            var splitter = new GridSplitter
            {
                Orientation = Orientation.Horizontal,
                [Grid.RowProperty] = 1,
            };
            var control2 = new Border { [Grid.RowProperty] = 2 };

            var rowDefinitions = new RowDefinitions()
            {
                new RowDefinition(1, GridUnitType.Star) {MinHeight = 70, MaxHeight = 110},
                new RowDefinition(GridLength.Auto),
                new RowDefinition(1, GridUnitType.Star) { MinHeight = 10, MaxHeight =  140},
            };

            var grid = new Grid()
            {
                RowDefinitions = rowDefinitions,
                Children = new Controls()
                {
                    control1, splitter, control2
                }
            };

            var root = new TestRoot { Child = grid };
            Assert.Equal(splitter.Orientation, Orientation.Horizontal);
            root.Measure(new Size(100, 200));
            root.Arrange(new Rect(0, 0, 100, 200));

            splitter.RaiseEvent(new VectorEventArgs
            {
                RoutedEvent = Thumb.DragDeltaEvent,
                Vector = new Vector(0, -100)
            });
            Assert.Equal(rowDefinitions[0].Height, new GridLength(70, GridUnitType.Star));
            Assert.Equal(rowDefinitions[2].Height, new GridLength(130, GridUnitType.Star));
            splitter.RaiseEvent(new VectorEventArgs
            {
                RoutedEvent = Thumb.DragDeltaEvent,
                Vector = new Vector(0, 100)
            });
            Assert.Equal(rowDefinitions[0].Height, new GridLength(110, GridUnitType.Star));
            Assert.Equal(rowDefinitions[2].Height, new GridLength(90, GridUnitType.Star));
        }
    private void SaveMyRoot()
    {
      // assumes dataobject is valid for save, should thest for IsSavable

      UnbindUI(false);
      try
      {
        MyRoot = MyRoot.Save();
      }
      catch (DataPortalException ex)
      {
        // Handle exception the way you waant
      }
      finally
      {
        BindUI();
      }
    }
        public void Nested_TemplatedControls_Should_Register_With_Correct_NameScope()
        {
            var target = new ContentControl
            {
                Template = new FuncControlTemplate<ContentControl>(ScrollingContentControlTemplate),
                Content = "foo"
            };

            var root = new TestRoot { Child = target };
            target.ApplyTemplate();

            var border = target.GetVisualChildren().FirstOrDefault();
            Assert.IsType<Border>(border);

            var scrollViewer = border.GetVisualChildren().FirstOrDefault();
            Assert.IsType<ScrollViewer>(scrollViewer);
            ((ScrollViewer)scrollViewer).ApplyTemplate();

            var scrollContentPresenter = scrollViewer.GetVisualChildren().FirstOrDefault();
            Assert.IsType<ScrollContentPresenter>(scrollContentPresenter);
            ((ContentPresenter)scrollContentPresenter).UpdateChild();

            var contentPresenter = scrollContentPresenter.GetVisualChildren().FirstOrDefault();
            Assert.IsType<ContentPresenter>(contentPresenter);

            var borderNs = NameScope.GetNameScope((Control)border);
            var scrollContentPresenterNs = NameScope.GetNameScope((Control)scrollContentPresenter);

            Assert.NotNull(borderNs);
            Assert.Same(scrollViewer, borderNs.Find("ScrollViewer"));
            Assert.Same(contentPresenter, borderNs.Find("PART_ContentPresenter"));
            Assert.Same(scrollContentPresenter, scrollContentPresenterNs.Find("PART_ContentPresenter"));
        }
Example #54
0
        public void Track_By_Name_Should_Track_Removal_And_Readd()
        {
            StackPanel panel;
            TextBlock target;
            TextBlock relativeTo;

            var root = new TestRoot
            {
                Child = panel = new StackPanel
                {
                    Children = new Controls.Controls
                    {
                        (target = new TextBlock { Name = "target" }),
                        (relativeTo = new TextBlock { Name = "start" }),
                    }
                }
            };

            var locator = ControlLocator.Track(relativeTo, "target");
            var result = new List<IControl>();
            locator.Subscribe(x => result.Add(x));

            var other = new TextBlock { Name = "target" };
            panel.Children.Remove(target);
            panel.Children.Add(other);

            Assert.Equal(new[] { target, null, other }, result);
        }
Example #55
0
        public void Templated_Control_With_Popup_In_Template_Should_Set_TemplatedParent()
        {
            using (CreateServices())
            {
                PopupContentControl target;
                var root = new TestRoot
                {
                    Child = target = new PopupContentControl
                    {
                        Content = new Border(),
                        Template = new ControlTemplate<PopupContentControl>(PopupContentControlTemplate),
                    }
                };

                target.ApplyTemplate();
                var popup = target.GetTemplateChild<Popup>("popup");
                popup.Open();
                var popupRoot = popup.PopupRoot;

                var children = popupRoot.GetVisualDescendents().ToList();
                var types = children.Select(x => x.GetType().Name).ToList();

                Assert.Equal(
                    new[]
                    {
                        "ContentPresenter",
                        "ContentPresenter",
                        "Border",
                    },
                    types);

                var templatedParents = children
                    .OfType<IControl>()
                    .Select(x => x.TemplatedParent).ToList();

                Assert.Equal(
                    new object[]
                    {
                        popupRoot,
                        target,
                        null,
                    },
                    templatedParents);
            }
        }
Example #56
0
        public void Clicking_Item_Should_Select_It()
        {
            var tree = CreateTestTreeData();
            var target = new TreeView
            {
                Template = CreateTreeViewTemplate(),
                Items = tree,
                DataTemplates = CreateNodeDataTemplate(),
            };

            var visualRoot = new TestRoot();
            visualRoot.Child = target;
            ApplyTemplates(target);

            var item = tree[0].Children[1].Children[0];
            var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item);

            Assert.NotNull(container);

            container.RaiseEvent(new PointerPressedEventArgs
            {
                RoutedEvent = InputElement.PointerPressedEvent,
                MouseButton = MouseButton.Left,
            });

            Assert.Equal(item, target.SelectedItem);
            Assert.True(container.IsSelected);
        }
Example #57
-1
        public void Vertical_Stays_Within_Constraints()
        {
            var cursorFactoryImpl = new Mock<IStandardCursorFactory>();
            PerspexLocator.CurrentMutable.Bind<IStandardCursorFactory>().ToConstant(cursorFactoryImpl.Object);

            var control1 = new Border { [Grid.ColumnProperty] = 0 };
            var splitter = new GridSplitter
            {
                Orientation = Orientation.Vertical,
                [Grid.ColumnProperty] = 1,
            };
            var control2 = new Border { [Grid.ColumnProperty] = 2 };

            var columnDefinitions = new ColumnDefinitions()
            {
                new ColumnDefinition(1, GridUnitType.Star) {MinWidth = 10, MaxWidth = 190},
                new ColumnDefinition(GridLength.Auto),
                new ColumnDefinition(1, GridUnitType.Star) {MinWidth = 80, MaxWidth =  120},
            };

            var grid = new Grid()
            {
                ColumnDefinitions = columnDefinitions,
                Children = new Controls()
                {
                    control1, splitter, control2
                }
            };

            var root = new TestRoot { Child = grid };
            Assert.Equal(splitter.Orientation, Orientation.Vertical);

            root.Measure(new Size(200, 100));
            root.Arrange(new Rect(0, 0, 200, 100));

            splitter.RaiseEvent(new VectorEventArgs
            {
                RoutedEvent = Thumb.DragDeltaEvent,
                Vector = new Vector(-100,0)
            });
            Assert.Equal(columnDefinitions[0].Width, new GridLength(80,GridUnitType.Star));
            Assert.Equal(columnDefinitions[2].Width, new GridLength(120,GridUnitType.Star));
            splitter.RaiseEvent(new VectorEventArgs
            {
                RoutedEvent = Thumb.DragDeltaEvent,
                Vector = new Vector(100, 0)
            });
            Assert.Equal(columnDefinitions[0].Width, new GridLength(120, GridUnitType.Star));
            Assert.Equal(columnDefinitions[2].Width, new GridLength(80, GridUnitType.Star));
        }