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",
            };

            target.Bind(TextBox.TextProperty, binding);

            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",
            };

            target.Bind(ContentControl.ContentProperty, binding);

            Assert.Same(source, target.Content);
        }
Пример #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);
        }
Пример #4
0
        public void Source_Should_Be_Used()
        {
            var source = new Source { Foo = "foo" };
            var binding = new Binding { Source = source, Path = "Foo" };
            var target = new TextBlock();

            target.Bind(TextBlock.TextProperty, binding);

            Assert.Equal(target.Text, "foo");
        }
        public async Task PropertyEquals_Matches_When_Property_Has_Matching_Value()
        {
            var control = new TextBlock();
            var target = default(Selector).PropertyEquals(TextBlock.TextProperty, "foo");
            var activator = target.Match(control).ObservableResult;

            Assert.False(await activator.Take(1));
            control.Text = "foo";
            Assert.True(await activator.Take(1));
            control.Text = null;
            Assert.False(await activator.Take(1));
        }
Пример #6
0
        public void Setter_Should_Apply_Binding_To_Property()
        {
            var control = new TextBlock();
            var subject = new BehaviorSubject<object>("foo");
            var descriptor = new InstancedBinding(subject);
            var binding = Mock.Of<IBinding>(x => x.Initiate(control, TextBlock.TextProperty, null, false) == descriptor);
            var style = Mock.Of<IStyle>();
            var setter = new Setter(TextBlock.TextProperty, binding);

            setter.Apply(style, control, null);

            Assert.Equal("foo", control.Text);
        }
Пример #7
0
        public static void Build(MainWindow window)
        {
            // maxRow y maxCol deberían estar definidas en el ViewModel...
            int  maxRow  = 9;
            int  maxCol  = 5;
            int  i       = 0;
            Grid grdMain = window.FindControl <Grid>("grdMain");

            for (int row = 0; row < maxRow; row++)
            {
                grdMain.RowDefinitions.Add(new RowDefinition {
                    Height = GridLength.Parse("*", CultureInfo.InstalledUICulture)
                });
            }
            for (int col = 0; col < maxCol; col++)
            {
                grdMain.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = GridLength.Parse("1*", CultureInfo.InstalledUICulture)
                });
            }
            for (int row = 0; row < maxRow; row++)
            {
                for (int col = 0; col < maxCol; col++)
                {
                    ButtonT b          = new ButtonT("Boton Nro: " + i.ToString(), i);
                    var     stackPanel = new Avalonia.Controls.StackPanel();
                    var     textBlock  = new Avalonia.Controls.TextBlock
                    {
                        [!TextBlock.TextProperty] = new Binding("Name")
                    };
                    stackPanel.Children.Add(textBlock);
                    var btn = new Avalonia.Controls.Button
                    {
                        Background = b.ButtonColor,
                        [!Button.BackgroundProperty] = b.ToBinding <SolidColorBrush>(),
                        [Grid.RowProperty]           = row,
                        [Grid.ColumnProperty]        = col,
                        // window.DataContext es null, por eso uso la instancia global del viewmodel :( )
                        Command          = ReactiveCommand.Create <ButtonT>(MainWindowViewModel.Instance.RunTheThing),
                        CommandParameter = b,
                        Content          = stackPanel,
                        DataContext      = b
                    };

                    i++;
                    grdMain.Children.Add(btn);
                }
            }
        }
        public void Initiate_Should_Enable_Data_Validation_With_BindingPriority_LocalValue()
        {
            var textBlock = new TextBlock
            {
                DataContext = new Class1(),
            };

            var target = new Binding(nameof(Class1.Foo));
            var instanced = target.Initiate(textBlock, TextBlock.TextProperty, enableDataValidation: true);
            var subject = (BindingExpression)instanced.Subject;
            object result = null;

            subject.Subscribe(x => result = x);

            Assert.Equal(new BindingNotification("foo"), result);
        }
        public void Initiate_Should_Not_Enable_Data_Validation_With_BindingPriority_TemplatedParent()
        {
            var textBlock = new TextBlock
            {
                DataContext = new Class1(),
            };

            var target = new Binding(nameof(Class1.Foo)) { Priority = BindingPriority.TemplatedParent };
            var instanced = target.Initiate(textBlock, TextBlock.TextProperty, enableDataValidation: true);
            var subject = (BindingExpression)instanced.Subject;
            object result = null;

            subject.Subscribe(x => result = x);

            Assert.IsType<string>(result);
        }
Пример #10
0
        public void OneWayToSource_Binding_Should_Be_Set_Up()
        {
            var source = new Source { Foo = "foo" };
            var target = new TextBlock { DataContext = source, Text = "bar" };
            var binding = new Binding
            {
                Path = "Foo",
                Mode = BindingMode.OneWayToSource,
            };

            target.Bind(TextBox.TextProperty, binding);

            Assert.Equal("bar", source.Foo);
            target.Text = "baz";
            Assert.Equal("baz", source.Foo);
            source.Foo = "quz";
            Assert.Equal("baz", target.Text);
        }
Пример #11
0
        public Form Panel <T>(string modelFieldName, Action <Form> populatePanel)
        {
            /*
             * Here is documentation on how ContentControl works:
             * https://docs.avaloniaui.net/docs/controls/contentcontrol
             */
            var panelControl = new Avalonia.Controls.ContentControl();

            if (!(getModelValue(modelFieldName) is T))
            {
                throw new Exception(
                          $"Model {nameof(modelFieldName)} source property specified by name [{modelFieldName}] is not of type T: {typeof(T).Name}");
            }

            /*
             * One Way binding, because the ContentControl cannot set the model back, it just displays the model
             */
            AddBinding <object>(modelFieldName: modelFieldName,
                                control: panelControl,
                                property: Avalonia.Controls.ContentControl.ContentProperty,
                                isTwoWayDataBinding: false);

            panelControl.ContentTemplate = new Avalonia.Controls.Templates.FuncDataTemplate <T>((itemModel, nameScope) =>
            {
                // if the model is null then just display nothing
                if (itemModel == null)
                {
                    // how could itemModel be null?  Sometimes it is though, so strange
                    var tb  = new Avalonia.Controls.TextBlock();
                    tb.Text = "(null)";
                    return(tb);
                }

                var contentForm         = new Form(__app: this.app, _model: new lib.BindableDynamicDictionary());
                contentForm.DataContext = itemModel;
                populatePanel(contentForm);

                contentForm.Host.DataContext = itemModel;
                return(contentForm.Host);
            });

            AddRowToHost(panelControl);
            return(this);
        }
Пример #12
0
        public void Should_Return_FallbackValue_When_Converter_Returns_UnsetValue()
        {
            var target = new TextBlock();
            var source = new { A = 1, B = 2, C = 3 };
            var binding = new MultiBinding
            {
                Converter = new UnsetValueConverter(),
                Bindings = new[]
                {
                    new Binding { Path = "A" },
                    new Binding { Path = "B" },
                    new Binding { Path = "C" },
                },
                FallbackValue = "fallback",
            };

            target.Bind(TextBlock.TextProperty, binding);

            Assert.Equal("fallback", target.Text);
        }
Пример #13
0
        public void Grandchild_Size_Changed()
        {
            using (var context = AvaloniaLocator.EnterScope())
            {
                RegisterServices();

                Border border;
                TextBlock textBlock;

                var window = new Window()
                {
                    SizeToContent = SizeToContent.WidthAndHeight,
                    Content = border = new Border
                    {
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                        Child = new Border
                        {
                            Child = textBlock = new TextBlock
                            {
                                Width = 400,
                                Height = 400,
                                Text = "Hello World!",
                            },
                        }
                    }
                };

                LayoutManager.Instance.ExecuteInitialLayoutPass(window);

                Assert.Equal(new Size(400, 400), border.Bounds.Size);
                textBlock.Width = 200;
                LayoutManager.Instance.ExecuteLayoutPass();

                Assert.Equal(new Size(200, 400), border.Bounds.Size);
            }
        }
Пример #14
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);
        }
Пример #15
0
        public void Should_Use_DefaultValueConverter_When_No_Converter_Specified()
        {
            var target = new TextBlock(); ;
            var binding = new Binding
            {
                Path = "Foo",
            };

            var result = binding.Initiate(target, TextBox.TextProperty).Subject;

            Assert.IsType<DefaultValueConverter>(((ExpressionSubject)result).Converter);
        }
Пример #16
0
        public void Test_ScrollViewer_With_TextBlock()
        {
            using (var context = AvaloniaLocator.EnterScope())
            {
                RegisterServices();

                ScrollViewer scrollViewer;
                TextBlock textBlock;

                var window = new Window()
                {
                    Width = 800,
                    Height = 600,
                    SizeToContent = SizeToContent.WidthAndHeight,
                    Content = scrollViewer = new ScrollViewer
                    {
                        Width = 200,
                        Height = 200,
                        CanScrollHorizontally = true,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                        Content = textBlock = new TextBlock
                        {
                            Width = 400,
                            Height = 400,
                            Text = "Hello World!",
                        },
                    }
                };

                LayoutManager.Instance.ExecuteInitialLayoutPass(window);

                Assert.Equal(new Size(800, 600), window.Bounds.Size);
                Assert.Equal(new Size(200, 200), scrollViewer.Bounds.Size);
                Assert.Equal(new Point(300, 200), Position(scrollViewer));
                Assert.Equal(new Size(400, 400), textBlock.Bounds.Size);

                var scrollBars = scrollViewer.GetTemplateChildren().OfType<ScrollBar>().ToList();
                var presenters = scrollViewer.GetTemplateChildren().OfType<ScrollContentPresenter>().ToList();

                Assert.Equal(2, scrollBars.Count);
                Assert.Equal(1, presenters.Count);

                var presenter = presenters[0];
                Assert.Equal(new Size(190, 190), presenter.Bounds.Size);

                var horzScroll = scrollBars.Single(x => x.Orientation == Orientation.Horizontal);
                var vertScroll = scrollBars.Single(x => x.Orientation == Orientation.Vertical);

                Assert.True(horzScroll.IsVisible);
                Assert.True(vertScroll.IsVisible);
                Assert.Equal(new Size(190, 10), horzScroll.Bounds.Size);
                Assert.Equal(new Size(10, 190), vertScroll.Bounds.Size);
                Assert.Equal(new Point(0, 190), Position(horzScroll));
                Assert.Equal(new Point(190, 0), Position(vertScroll));
            }
        }
Пример #17
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);
        }
Пример #18
0
        public override bool ApplyTemplate()
        {
            if (this.IsInitialized && this.visualChild == null)
            {
                Visual visual = this.Content as Visual;

                if (visual == null && this.Content != null)
                {
                    DataTemplate template = this.ContentTemplate;

                    if (template == null)
                    {
                        DataTemplateKey key = new DataTemplateKey(this.Content.GetType());
                        template = this.TryFindResource(key) as DataTemplate;
                    }

                    if (template != null)
                    {
                        visual = template.CreateVisualTree(this);

                        FrameworkElement fe = visual as FrameworkElement;

                        if (fe != null)
                        {
                            fe.DataContext = this.Content;
                        }
                    }
                    else
                    {
                        visual = new TextBlock
                        {
                            Text = this.Content.ToString(),
                        };
                    }
                }

                if (visual != null)
                {
                    this.visualChild = visual;
                    this.AddVisualChild(this.visualChild);
                    this.OnApplyTemplate();
                    return true;
                }
            }

            return false;
        }
Пример #19
0
        private static void UpdateXaml2(Dictionary<string, object> dic)
        {
            var xamlInfo = new DesignerApiXamlFileInfo(dic);
            Window window;
            Control control;

            using (PlatformManager.DesignerMode())
            {
                var loader = new AvaloniaXamlLoader();
                var stream = new MemoryStream(Encoding.UTF8.GetBytes(xamlInfo.Xaml));


                
                Uri baseUri = null;
                if (xamlInfo.AssemblyPath != null)
                {
                    //Fabricate fake Uri
                    baseUri =
                        new Uri("resm:Fake.xaml?assembly=" + Path.GetFileNameWithoutExtension(xamlInfo.AssemblyPath));
                }

                var loaded = loader.Load(stream, null, baseUri);
                var styles = loaded as Styles;
                if (styles != null)
                {
                    var substitute = Design.GetPreviewWith(styles) ??
                                     styles.Select(Design.GetPreviewWith).FirstOrDefault(s => s != null);
                    if (substitute != null)
                    {
                        substitute.Styles.AddRange(styles);
                        control = substitute;
                    }
                    else
                        control = new StackPanel
                        {
                            Children =
                            {
                                new TextBlock {Text = "Styles can't be previewed without Design.PreviewWith. Add"},
                                new TextBlock {Text = "<Design.PreviewWith>"},
                                new TextBlock {Text = "    <Border Padding=20><!-- YOUR CONTROL FOR PREVIEW HERE--></Border>"},
                                new TextBlock {Text = "<Design.PreviewWith>"},
                                new TextBlock {Text = "before setters in your first Style"}
                            }
                        };
                }
                if (loaded is Application)
                    control = new TextBlock {Text = "Application can't be previewed in design view"};
                else
                    control = (Control) loaded;

                window = control as Window;
                if (window == null)
                {
                    window = new Window() {Content = (Control)control};
                }

                if (!window.IsSet(Window.SizeToContentProperty))
                    window.SizeToContent = SizeToContent.WidthAndHeight;
            }

            s_currentWindow?.Close();
            s_currentWindow = window;
            window.Show();
            Design.ApplyDesignerProperties(window, control);
            Api.OnWindowCreated?.Invoke(window.PlatformImpl.Handle.Handle);
            Api.OnResize?.Invoke();
        }
        public Form DropDown <T>(string itemSourceModelName,
                                 string selectedItemModelName,
                                 Action <T> onSelectionChanged = null,
                                 Action <Form> populateItemRow = null,
                                 model.Style style             = null)
        {
            var dp = new Avalonia.Controls.ComboBox();

            lib.styleUtil.style(this, dp, style);

            // Just as a safety check, make them init the model first
            if (!(getModelValue(itemSourceModelName) is IEnumerable <T>))
            {
                throw new Exception($"Model {nameof(itemSourceModelName)} source property specified by name [{itemSourceModelName}] must be a IEnumerable<T>");
            }


            // item source binding
            AddBinding <IEnumerable>(modelFieldName: itemSourceModelName,
                                     control: dp,
                                     property: Avalonia.Controls.ComboBox.ItemsProperty,
                                     isTwoWayDataBinding: false);

            // selected item binding
            AddBinding <object>(modelFieldName: selectedItemModelName,
                                control: dp,
                                property: Avalonia.Controls.ComboBox.SelectedItemProperty,
                                isTwoWayDataBinding: true);

            if (populateItemRow != null)
            {
                dp.ItemTemplate = new FuncDataTemplate <object>((itemModel, nameScope) =>
                {
                    if (itemModel == null)
                    {
                        // how could itemModel be null?  Sometimes it is though, so strange
                        var tb  = new Avalonia.Controls.TextBlock();
                        tb.Text = "(null)";
                        return(tb);
                    }

                    var rowForm = new Form(__app: this.app, _model: new lib.BindableDynamicDictionary());
                    // this has to have a unique model
                    rowForm.DataContext = itemModel;
                    populateItemRow(rowForm);

                    rowForm.Host.DataContext = itemModel;

                    return(rowForm.Host);
                });
            }



            dp.SelectionChanged += (_s, _args) =>
            {
                if (_args.AddedItems.OfType <T>().Any())
                {
                    var first = _args.AddedItems.Cast <T>().First();
                    onSelectionChanged?.Invoke(first);
                }
            };

            AddRowToHost(dp);
            return(this);
        }
Пример #21
0
        public void Should_Pass_ConverterParameter_To_Supplied_Converter()
        {
            var target = new TextBlock();
            var converter = new Mock<IValueConverter>();
            var binding = new Binding
            {
                Converter = converter.Object,
                ConverterParameter = "foo",
                Path = "Bar",
            };

            var result = binding.Initiate(target, TextBox.TextProperty).Subject;

            Assert.Same("foo", ((BindingExpression)result).ConverterParameter);
        }
        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",
            };

            target.Bind(ContentControl.ContentProperty, binding);

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

            stackPanel.Children.Add(source);

            Assert.Same(source, target.Content);
        }
Пример #23
0
        public void Should_Use_Supplied_Converter()
        {
            var target = new TextBlock();
            var converter = new Mock<IValueConverter>();
            var binding = new Binding
            {
                Converter = converter.Object,
                Path = "Foo",
            };

            var result = binding.Initiate(target, TextBox.TextProperty).Subject;

            Assert.Same(converter.Object, ((ExpressionSubject)result).Converter);
        }
Пример #24
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);
        }
Пример #25
0
        public void Should_Return_FallbackValue_When_Path_Not_Resolved()
        {
            var target = new TextBlock();
            var source = new Source();
            var binding = new Binding
            {
                Source = source,
                Path = "BadPath",
                FallbackValue = "foofallback",
            };

            target.Bind(TextBlock.TextProperty, binding);

            Assert.Equal("foofallback", target.Text);
        }