コード例 #1
0
		public static void ApplyForegroundToFillBinding(ContentControl control)
		{
			if (control == null)
				return;

			var element = control.Content as FrameworkElement;

			if (element == null) 
				return;

			if (System.TypeExtensions.IsTypeOf(element, typeof(Shape)))
			{
				var shape = element as Shape;

				ResetVerifyAndApplyForegroundToFillBinding(control, shape);
			}
			else
			{
				var children = element.GetLogicalChildrenByType<Shape>(false);

				foreach (var child in children)
				{
					var hash = child.GetHashCode();

					ResetVerifyAndApplyForegroundToFillBinding(control, child);
				}
			}
		}
コード例 #2
0
        public void GetVisualParents() {
#endif
            Grid grid = new Grid();
            ContentControl contentControl = new ContentControl();
            TextBox textBox;
            Window.Content = grid;
            grid.Children.Add(contentControl);
            contentControl.ContentTemplate = textBoxTemplate;
#if NETFX_CORE
            await
#endif
            EnqueueShowWindow();
            EnqueueCallback(() => {
                textBox = (TextBox)LayoutHelper.FindElement(contentControl, x => x is TextBox);
                Assert.AreSame(contentControl, LayoutTreeHelper.GetVisualParents(textBox).Where(x => x is ContentControl).First());
                Assert.AreSame(grid, LayoutTreeHelper.GetVisualParents(textBox).Where(x => x is Grid).First());
                Assert.AreSame(Window, LayoutTreeHelper.GetVisualParents(textBox).Where(x => x.GetType() == Window.GetType()).First());

                Assert.AreSame(contentControl, LayoutTreeHelper.GetVisualParents(textBox, contentControl).Where(x => x is ContentControl).First());
                Assert.IsNull(LayoutTreeHelper.GetVisualParents(textBox, contentControl).Where(x => x is Grid).FirstOrDefault());

                var presenter = LayoutTreeHelper.GetVisualChildren(contentControl).First();
                Assert.IsTrue(new[] { presenter }.SequenceEqual(LayoutTreeHelper.GetVisualParents(textBox, presenter)));
            });
            EnqueueTestComplete();
        }
 /// <summary>
 /// Appends the content control.
 /// </summary>
 /// <param name="contentControl">The content control.</param>
 /// <param name="json">The json.</param>
 private void AppendContentControl(ContentControl contentControl, StringBuilder json)
 {
     json.Append(string.Format("{{\"title\":\"{0}\", \"startPage\":{1}, \"endPage\":{2}}}",
         JsonEncode(contentControl.Title),
         contentControl.StartPageNumber.ToString(_defaultCulture),
         contentControl.EndPageNumber.ToString(_defaultCulture)));
 }
コード例 #4
0
 void CreateTemplateTestCore(DataTemplate dataTemplate) {
     ContentControl content = new ContentControl() { ContentTemplate = dataTemplate };
     Window.Content = content;
     EnqueueShowWindow();
     EnqueueCallback(() => {
         Assert.IsNotNull(LayoutTreeHelper.GetVisualChildren(content).OfType<TestView1>().FirstOrDefault());
     });
     EnqueueTestComplete();
 }
コード例 #5
0
        public void Setting_Content_Should_Initialize_Control()
        {
            ContentControl target = new ContentControl();
            TextBlock child = new TextBlock();

            Assert.IsFalse(target.IsInitialized);
            target.Content = child;
            Assert.IsTrue(target.IsInitialized);
        }
コード例 #6
0
		public static void ApplyTitleOffset(ContentControl contentTitle)
		{
			if (contentTitle == null) 
				return;

			var bottom = -(contentTitle.FontSize / 8.0);
			var top = -(contentTitle.FontSize / 2.0) - bottom;

			contentTitle.Margin = new Thickness(0, top, 0, bottom);
		}
コード例 #7
0
        public void Measure_Should_Call_Child_Measure()
        {
            ContentControl target = new ContentControl();
            ChildControl child = new ChildControl();

            child.RecordInputs = true;
            target.Content = child;           
            target.Measure(new Size(12, 23));

            Assert.AreEqual(new Size(12, 23), child.MeasureInput);
        }
コード例 #8
0
 private Control CreateNestedTemplate(ContentControl control)
 {
     return new ScrollViewer
     {
         Template = new FuncControlTemplate<ScrollViewer>(CreateTemplate),
         Content = new ContentPresenter
         {
             Name = "PART_ContentPresenter",
         }
     };
 }
コード例 #9
0
        public void Content_Should_Have_TemplatedParent_Set_To_Null()
        {
            var target = new ContentControl();
            var child = new Border();

            target.Template = GetTemplate();
            target.Content = child;
            target.ApplyTemplate();

            Assert.Null(child.TemplatedParent);
        }
コード例 #10
0
        public void ContentPresenter_Should_Have_TemplatedParent_Set()
        {
            var target = new ContentControl();
            var child = new Border();

            target.Template = GetTemplate();
            target.Content = child;
            target.ApplyTemplate();

            var contentPresenter = child.GetVisualParent<ContentPresenter>();
            Assert.Equal(target, contentPresenter.TemplatedParent);
        }
コード例 #11
0
		public override void OnApplyTemplate()
#endif
		{
			base.OnApplyTemplate();

			HintContentElement = GetTemplateChild(HintContentElementName) as ContentControl;

			UpdateHintVisibility();
			UpdateChatBubbleDirection();

            UpdateIsEquallySpaced();
		}
コード例 #12
0
        public void Full_Size_Should_Be_Passed_To_Child_ArrangeOverride_For_Stretch_Alignment()
        {
            ContentControl target = new ContentControl();
            ChildControl child = new ChildControl();

            child.RecordInputs = true;
            child.MeasureOutput = new Size(12, 23);
            target.Content = child;
            target.Arrange(new Rect(new Point(34, 45), new Size(56, 67)));

            Assert.AreEqual(new Size(56, 67), child.ArrangeInput);
        }
コード例 #13
0
        public void Measure_Width_Should_Be_Passed_To_Child_ArrangeOverride_For_Right_Alignment()
        {
            ContentControl target = new ContentControl();
            ChildControl child = new ChildControl();

            child.RecordInputs = true;
            child.HorizontalAlignment = HorizontalAlignment.Right;
            child.MeasureOutput = new Size(12, 23);
            target.Content = child;
            target.Arrange(new Rect(new Point(34, 45), new Size(56, 67)));

            Assert.AreEqual(new Size(12, 67), child.ArrangeInput);
        }
コード例 #14
0
        public void Clearing_Content_Should_Clear_Logical_Child()
        {
            var target = new ContentControl();
            var child = new Control();

            target.Content = child;

            Assert.Equal(new[] { child }, target.GetLogicalChildren());

            target.Content = null;

            Assert.Null(child.Parent);
            Assert.Null(child.GetLogicalParent());
            Assert.Empty(target.GetLogicalChildren());
        }
コード例 #15
0
        public void Template_Should_Be_Instantiated()
        {
            var target = new ContentControl();
            target.Content = "Foo";
            target.Template = GetTemplate();
            target.ApplyTemplate();
            ((ContentPresenter)target.Presenter).UpdateChild();

            var child = ((IVisual)target).VisualChildren.Single();
            Assert.IsType<Border>(child);
            child = child.VisualChildren.Single();
            Assert.IsType<ContentPresenter>(child);
            child = child.VisualChildren.Single();
            Assert.IsType<TextBlock>(child);
        }
コード例 #16
0
        public void Changing_Content_Should_Update_Presenter()
        {
            var target = new ContentControl();

            target.Template = GetTemplate();
            target.ApplyTemplate();
            ((ContentPresenter)target.Presenter).UpdateChild();

            target.Content = "Foo";
            ((ContentPresenter)target.Presenter).UpdateChild();
            Assert.Equal("Foo", ((TextBlock)target.Presenter.Child).Text);
            target.Content = "Bar";
            ((ContentPresenter)target.Presenter).UpdateChild();
            Assert.Equal("Bar", ((TextBlock)target.Presenter.Child).Text);
        }
コード例 #17
0
        public void Template_Should_Be_Instantiated()
        {
            using (var ctx = RegisterServices())
            {
                var target = new ContentControl();
                target.Content = "Foo";
                target.Template = GetTemplate();

                target.Measure(new Size(100, 100));

                var child = ((IVisual)target).VisualChildren.Single();
                Assert.IsType<Border>(child);
                child = child.VisualChildren.Single();
                Assert.IsType<ContentPresenter>(child);
                child = child.VisualChildren.Single();
                Assert.IsType<TextBlock>(child);
            }
        }
コード例 #18
0
        public void Templated_Children_Should_Be_Styled()
        {
            var root = new TestRoot();
            var target = new ContentControl();
            var styler = new Mock<IStyler>();

            AvaloniaLocator.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());
        }
コード例 #19
0
        public void Changing_Content_Should_Fire_LogicalChildren_CollectionChanged()
        {
            var target = new ContentControl();
            var child1 = new Control();
            var child2 = new Control();
            var called = false;

            target.Template = GetTemplate();
            target.Content = child1;
            target.ApplyTemplate();
            ((ContentPresenter)target.Presenter).UpdateChild();

            ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true;

            target.Content = child2;
            target.Presenter.ApplyTemplate();

            Assert.True(called);
        }
コード例 #20
0
        public void GetVisualChildren() {
#endif
            Grid grid = new Grid();
            ContentControl contentControl = new ContentControl();
            TextBox textBox;
            Window.Content = grid;
            grid.Children.Add(contentControl);
            contentControl.ContentTemplate = textBoxTemplate;
#if NETFX_CORE
            await
#endif
            EnqueueShowWindow();
            EnqueueCallback(() => {
                textBox = (TextBox)LayoutHelper.FindElement(contentControl, x => x is TextBox);

                Assert.AreSame(contentControl, LayoutTreeHelper.GetVisualChildren(grid).Where(x => x is ContentControl).FirstOrDefault());
                Assert.AreSame(textBox, LayoutTreeHelper.GetVisualChildren(grid).Where(x => x is TextBox).FirstOrDefault());
            });
            EnqueueTestComplete();
        }
コード例 #21
0
        public void Templated_Children_Should_Be_Styled()
        {
            using (var ctx = RegisterServices())
            {
                var root = new TestRoot();
                var target = new ContentControl();
                var styler = new Mock<IStyler>();

                Locator.CurrentMutable.Register(() => styler.Object, typeof(IStyler));
                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());
            }
        }
コード例 #22
0
ファイル: Attached.cs プロジェクト: mijgame/Icons.Avalonia
 public static string GetIcon(ContentControl target)
 {
     return(target.GetValue(IconProperty));
 }
コード例 #23
0
ファイル: HtmlToDocx.cs プロジェクト: SoftServeInc/SALMA
        /// <summary>
        /// Convert html to docx
        /// </summary>
        /// <param name="control"></param>
        /// <param name="html"></param>
        public void ToDocx(ContentControl control, string html)
        {
            int actionCount = 0;

            string ra = Convert.ToChar(0x000D).ToString() + Convert.ToChar(0x0007).ToString(); // \r\a
            string folderName = Path.GetTempPath() + Guid.NewGuid().ToString(); // temp folder
            string fileName = folderName + "\\temp.docx"; // temp file
            string controlID = control.ID;

            Range range = control.Range;

            Globals.ThisAddIn.Application.ScreenUpdating = false; // false to update screen

            Microsoft.Office.Interop.Word.Document doc = null;

            try
            {
                // get wi id and field name
                string wiID = Globals.ThisAddIn.Application.ActiveDocument.Variables[control.ID + "_wiid"].Value;
                string wiField = Globals.ThisAddIn.Application.ActiveDocument.Variables[control.ID + "_wifield"].Value;

                CreateTempDocument(html, folderName, fileName);

                // get range to insert
                doc = Globals.ThisAddIn.Application.Documents.Open(fileName, Visible: false, ReadOnly: true);
                Range insert = doc.Content;
                PrepareRange(ref range, ref insert);

                // delete old control

                Globals.ThisAddIn.Application.ActiveDocument.Range(range.Start - 1, range.End + 1).Select();
                if (wiField != "System.Title") Globals.ThisAddIn.Application.Selection.ClearFormatting(); actionCount++;

                control.Delete(true); actionCount++;

                // insert range
                if (wiField != "System.Title") { range.FormattedText = insert.FormattedText; actionCount++; }
                else { range.Text = insert.Text; actionCount++; }

                range.LanguageID = WdLanguageID.wdNoProofing;

                foreach (InlineShape image in range.InlineShapes)
                    image.LinkFormat.SavePictureWithDocument = true;

                range.Select();
                ExtendSelection();

                Globals.ThisAddIn.Application.ActiveDocument.Range(range.End, range.End + 1).Delete(); actionCount++;

                // add new control
                int id = 0;

                if (Int32.TryParse(wiID, out id))
                    Globals.ThisAddIn.AddWIControl(id, wiField, range);
            }
            catch (Exception e)
            {
                if (actionCount > 0)
                    Globals.ThisAddIn.Application.ActiveDocument.Undo(actionCount);

                throw new Exception(e.Message);
            }
            finally
            {
                Globals.ThisAddIn.Application.Selection.Collapse();
                Globals.ThisAddIn.Application.ScreenUpdating = true;

                try
                {
                    ((_Document)doc).Close(SaveChanges: false);

                    if (Directory.Exists(folderName))
                        Directory.Delete(folderName, true);
                }
                catch { }
            }

            DeleteVariables(controlID);
        }
コード例 #24
0
 protected internal bool Type; //true = examination, false = evidence
 protected internal DocumentControlVM(ref ContentControl content, ObservableCollection <DocumentControlM.ListElement> List)
 {
     local = content;
     DocumentControlM.List = List;
 }
コード例 #25
0
        /// <summary>
        /// 初始化MainWindow类的新实例
        /// Initializes a new instance of the MainWindow class
        /// </summary>
        public MainWindow()
        {
            // only one sensor is currently supported
            //当前只有一个传感器被支持
            this.kinectSensor = KinectSensor.GetDefault();

            // set IsAvailableChanged event notifier
            //设置IsAvailableChanged事件通知程序
            this.kinectSensor.IsAvailableChanged += this.Sensor_IsAvailableChanged;

            // open the sensor
            //打开kinect
            this.kinectSensor.Open();

            // set the status text
            //设置状态正文
            this.StatusText = this.kinectSensor.IsAvailable ? Properties.Resources.RunningStatusText
                                                            : Properties.Resources.NoSensorStatusText;

            // open the reader for the body frames
            //打开身体框架阅读器
            this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader();

            // set the BodyFramedArrived event notifier
            // 设置BodyFramedArrived事件通知程序
            this.bodyFrameReader.FrameArrived += this.Reader_BodyFrameArrived;

            // initialize the BodyViewer object for displaying tracked bodies in the UI
            // 初始化BodyViewer对象以在UI中显示跟踪的实体
            this.kinectBodyView = new KinectBodyView(this.kinectSensor);

            // initialize the gesture detection objects for our gestures
            // 为我们的手势初始化手势检测对象
            this.gestureDetectorList = new List <GestureDetector>();

            // initialize the MainWindow
            // 初始化主窗口
            this.InitializeComponent();

            // set our data context objects for display in UI
            // 设置我们的数据上下文对象以在UI中显示
            this.DataContext = this;
            this.kinectBodyViewbox.DataContext = this.kinectBodyView;

            // create a gesture detector for each body (6 bodies => 6 detectors) and create content controls to display results in the UI
            // 为每个身体创建一个手势检测器(6个身体=> 6个检测器)并创建内容控件以在UI中显示结果
            int col0Row   = 0;
            int col1Row   = 0;
            int maxBodies = this.kinectSensor.BodyFrameSource.BodyCount;

            for (int i = 0; i < maxBodies; ++i)
            {
                GestureResultView result   = new GestureResultView(i, false, false, 0.0f);
                GestureDetector   detector = new GestureDetector(this.kinectSensor, result);
                this.gestureDetectorList.Add(detector);

                // split gesture results across the first two columns of the content grid
                // 在内容网格的前两列中分割手势结果
                ContentControl contentControl = new ContentControl();
                contentControl.Content = this.gestureDetectorList[i].GestureResultView;

                if (i % 2 == 0)
                {
                    // Gesture results for bodies: 0, 2, 4
                    // 身体的手势结果:0,2,4
                    Grid.SetColumn(contentControl, 0);
                    Grid.SetRow(contentControl, col0Row);
                    ++col0Row;
                }
                else
                {
                    // Gesture results for bodies: 1, 3, 5
                    //身体的手势结果:1,3,5
                    Grid.SetColumn(contentControl, 1);
                    Grid.SetRow(contentControl, col1Row);
                    ++col1Row;
                }

                this.contentGrid.Children.Add(contentControl);
            }
        }
コード例 #26
0
        public MultiWindowPresenter(ContentControl mainWindow)
        {
            this.mainWindow = mainWindow;

            //modalWindow
        }
コード例 #27
0
 //TODO: implement xamarin view to UWP
 private async void TransformXamarinViewToUWPBitmap(Pin outerItem, ContentControl nativeItem)
 {
     if (outerItem?.Icon?.Type == BitmapDescriptorType.View && outerItem?.Icon?.View != null)
     {
     }
 }
コード例 #28
0
        private void BuildDynamicGrid(ContentControl grid)
        {
            if (grid == null)
            {
                return;
            }


            PropertyInfo itemsProperty = DataContext.GetInstanceProperties().FirstOrDefault(pi => pi.Name == "Items");
            DataGrid     gridControl   = ItemsControlProvider.ProvideGridControl(itemsProperty, DataContext);

            if (SelectedItemBinding != null)
            {
                gridControl.SetBinding(Selector.SelectedItemProperty, SelectedItemBinding);
            }


            //set datagrid queryable sorting
            gridControl.Sorting += (o, e) =>
            {
                var dc = DataContext as IPagedQueryable;
                if (dc == null)
                {
                    return;
                }

                if (e.Column.SortDirection.HasValue == false ||
                    e.Column.SortDirection.Value == ListSortDirection.Descending)
                {
                    dc.BeginInit();
                    dc.SortColumn    = e.Column.SortMemberPath;
                    dc.SortDirection = (SortDirection)ListSortDirection.Ascending;
                    dc.EndInit();
                    e.Column.SortDirection = ListSortDirection.Ascending;
                }
                else
                {
                    dc.BeginInit();
                    dc.SortColumn    = e.Column.SortMemberPath;
                    dc.SortDirection = (SortDirection)ListSortDirection.Descending;
                    dc.EndInit();
                    e.Column.SortDirection = ListSortDirection.Descending;
                }
                e.Handled = true;
            };


            gridControl.SelectionChanged += (o, e) =>
            {
                var gc = o as DataGrid;
                if (gc == null)
                {
                    return;
                }

                var dc = gc.DataContext as IPagedQueryable;
                if (dc == null)
                {
                    return;
                }

                dc.ChangeSelection(e.RemovedItems, e.AddedItems);
            };

            gridControl.MouseDown += (o, e) =>
            {
                var gc = o as DataGrid;
                if (gc == null)
                {
                    return;
                }

                var dc = gc.DataContext as IPagedQueryable;
                if (dc == null)
                {
                    return;
                }

                if (e.ChangedButton == MouseButton.XButton1)
                {
                    if (dc.CanMovePrevious)
                    {
                        dc.MovePrevious();
                    }
                }
                if (e.ChangedButton == MouseButton.XButton2)
                {
                    if (dc.CanMoveNext)
                    {
                        dc.MoveNext();
                    }
                }
            };

            gridControl.Unloaded += (o, e) =>
            {
                var control = o as DataGrid;
                if (control == null)
                {
                    return;
                }

                BindingOperations.ClearAllBindings(control);
            };

            grid.SetValue(ContentControl.ContentProperty, gridControl);
        }
コード例 #29
0
        public void SelectedItemBinding()
        {
            TreeView treeView = new TreeView();
            treeView.ItemsSource = "some test text".Split();
            ContentControl contentControl = new ContentControl();
            Binding binding = new Binding("SelectedItem");
            binding.Source = treeView;
            contentControl.SetBinding(ContentControl.ContentProperty, binding);

            StackPanel panel = new StackPanel();
            panel.Children.Add(treeView);
            panel.Children.Add(contentControl);

            TreeViewItem treeViewItem = null;

            TestAsync(
                panel,
                () => treeViewItem = ((TreeViewItem)(treeView.ItemContainerGenerator.ContainerFromIndex(1))),
                () => treeViewItem.IsSelected = true,
                () => Assert.AreEqual("test", treeView.SelectedItem),
                () => Assert.AreEqual("test", contentControl.Content));
        }
コード例 #30
0
 public void NameScopeAccessProviderSourceTest() {
     var window = new ContentControl();
     var eventToCommand = new EventToCommand();
     var testViewModel = new TestViewModel();
     window.Content = testViewModel;
     int execCount = 0;
     eventToCommand.Command = new DelegateCommand(() => execCount++);
     eventToCommand.SourceObject = testViewModel;
     eventToCommand.EventName = "TestEvent";
     Interaction.GetBehaviors(window).Add(eventToCommand);
     testViewModel.RaiseTestEvent();
     Assert.AreEqual(1, execCount);
 }
コード例 #31
0
 public static void SerializeContentTo([NotNull] this ContentControl control, [NotNull] Stream stream) => XamlWriter.Save(control.Content, stream);
コード例 #32
0
 public static void SerializeContentTo([NotNull] this ContentControl control, [NotNull] TextWriter writer) => XamlWriter.Save(control.Content, writer);
コード例 #33
0
 public static void DeserializeContentFrom([NotNull] this ContentControl control, [NotNull] Stream stream) => control.Content = XamlReader.Load(stream);
コード例 #34
0
 public static void DeserializeContentFrom([NotNull] this ContentControl control, TextReader reader) => control.DeserializeContentFrom(XmlReader.Create(reader));
コード例 #35
0
 public static void DeserializeContentFrom([NotNull] this ContentControl control, [NotNull] XmlReader reader) => control.Content = XamlReader.Load(reader);
コード例 #36
0
 private static IControl ScrollingContentControlTemplate(ContentControl control)
 {
     return new Border
     {
         Child = new ScrollViewer
         {
             Template = new FuncControlTemplate<ScrollViewer>(ScrollViewerTemplate),
             Name = "ScrollViewer",
             Content = new ContentPresenter
             {
                 Name = "PART_ContentPresenter",
                 [!ContentPresenter.ContentProperty] = control[!ContentControl.ContentProperty],
             }
         }
     };
 }
コード例 #37
0
        /// <summary>
        /// Creates the error control.
        /// </summary>
        public virtual ContentControl CreateErrorControl(PropertyItem pi, object instance, Tab tab, PropertyControlFactoryOptions options)
        {
            var dataErrorInfoInstance       = instance as IDataErrorInfo;
            var notifyDataErrorInfoInstance = instance as INotifyDataErrorInfo;

            var errorControl = new ContentControl
            {
                ContentTemplate = options.ValidationErrorTemplate,
                Focusable       = false
            };
            IValueConverter errorConverter;
            string          propertyPath;
            object          source = null;

            if (dataErrorInfoInstance != null)
            {
                errorConverter = new DataErrorInfoConverter(dataErrorInfoInstance, pi.PropertyName);
                propertyPath   = pi.PropertyName;
                source         = instance;
            }
            else
            {
                errorConverter = new NotifyDataErrorInfoConverter(notifyDataErrorInfoInstance, pi.PropertyName);
                propertyPath   = nameof(tab.HasErrors);
                source         = tab;
                notifyDataErrorInfoInstance.ErrorsChanged += (s, e) =>
                {
                    tab.UpdateHasErrors(notifyDataErrorInfoInstance);
                };
            }

            var visibilityBinding = new Binding(propertyPath)
            {
                Converter             = errorConverter,
                NotifyOnTargetUpdated = true,
#if !NET40
                ValidatesOnNotifyDataErrors = false,
#endif
                Source = source,
            };

            var contentBinding = new Binding(propertyPath)
            {
                Converter = errorConverter,
#if !NET40
                ValidatesOnNotifyDataErrors = false,
#endif
                Source = source,
            };

            errorControl.SetBinding(UIElement.VisibilityProperty, visibilityBinding);

            // When the visibility of the error control is changed, updated the HasErrors of the tab
            errorControl.TargetUpdated += (s, e) =>
            {
                if (dataErrorInfoInstance != null)
                {
                    tab.UpdateHasErrors(dataErrorInfoInstance);
                }
            };
            errorControl.SetBinding(ContentControl.ContentProperty, contentBinding);
            return(errorControl);
        }
コード例 #38
0
 public JoystickControl(ContentControl contentControl, Library library)
 {
     InitializeComponent();
     _library        = library;
     _contentControl = contentControl;
 }
コード例 #39
0
 public AbstractConnector(IConnector parent, ContentControl ui)
 {
     Parent = parent;
     Ui     = ui;
 }
コード例 #40
0
        /// <summary>This method is invoked when application is in idle state</summary>
        void IdleDraw(object sender, EventArgs e)
        {
            bool finished = true;

            SyncMarkerViewModels();
            // Remove extra batches. Such removals take a lot of time, so we do it at idle handlers
            if (batches.Count > Math.Ceiling(models.Count / (double)MarkersBatchSize))
            {
                var b = batches[batches.Count - 1];
                Children.Remove(b.Panel);
                Children.Remove(b.Image);
                batches.RemoveAt(batches.Count - 1);
                finished = false;
            }
            // Find first batch that is ready for Image updating
            var batch = batches.FirstOrDefault(b => b.PanelVersion == plotVersion &&
                                               b.Panel.Visibility == System.Windows.Visibility.Visible &&
                                               b.IsLayoutUpdated &&
                                               b.ImageVersion != plotVersion);

            if (batch != null)
            {
                batch.PlotRect = ActualPlotRect;
                var panelSize  = new Size(Math.Max(1, batch.Panel.RenderSize.Width), Math.Max(1, batch.Panel.RenderSize.Height));
                var renderSize = new Size(
                    Math.Min(MaxSnapshotSize.Width, panelSize.Width),
                    Math.Min(MaxSnapshotSize.Height, panelSize.Height));
                if (batch.Content == null || batch.Content.PixelWidth != (int)Math.Ceiling(renderSize.Width) || batch.Content.PixelHeight != (int)Math.Ceiling(renderSize.Height))
                {
                    batch.Content = new RenderTargetBitmap((int)renderSize.Width, (int)renderSize.Height, 96, 96, PixelFormats.Pbgra32);
                }
                else
                {
                    batch.Content.Clear();
                }

                ScaleTransform transform = new ScaleTransform
                {
                    ScaleX = renderSize.Width < panelSize.Width ? renderSize.Width / panelSize.Width : 1.0,
                    ScaleY = renderSize.Height < panelSize.Height ? renderSize.Height / panelSize.Height : 1.0
                };
                var panel = batch.Panel;
                panel.RenderTransform = transform;
                batch.Content         = new RenderTargetBitmap((int)renderSize.Width, (int)renderSize.Height, 96, 96, PixelFormats.Pbgra32);
                batch.Content.Render(panel);
                batch.ImageVersion = plotVersion;
                finished           = false;
            }
            // Find first batch that should be rendered
            batch = batches.FirstOrDefault(b => b.PanelVersion != plotVersion);
            if (batch != null)
            {
                int idx = batches.IndexOf(batch);
                if (!batch.Panel.IsMaster && idx * MarkersBatchSize < models.Count)
                {
                    if (MarkerTemplate == null)
                    {
                        batch.Panel.Children.Clear();
                    }
                    else
                    {
                        int batchSize = Math.Min(MarkersBatchSize, models.Count - idx * MarkersBatchSize);
                        while (batch.Panel.Children.Count > batchSize)
                        {
                            batch.Panel.Children.RemoveAt(batch.Panel.Children.Count - 1);
                        }
                        for (int i = 0; i < batch.Panel.Children.Count; i++)
                        {
                            var mvm = models[i + idx * MarkersBatchSize];
                            var fe  = batch.Panel.Children[i] as FrameworkElement;
                            if (fe.DataContext != mvm)
                            {
                                fe.DataContext = mvm;
                            }
                            else
                            {
                                mvm.Notify(batch.ChangedProperties);
                            }
                        }
                        for (int i = batch.Panel.Children.Count; i < batchSize; i++)
                        {
                            var fe = MarkerTemplate.LoadContent() as FrameworkElement;
                            fe.DataContext = models[i + idx * MarkersBatchSize];
                            if (TooltipTemplate != null)
                            {
                                var tc = new ContentControl
                                {
                                    Content         = fe.DataContext,
                                    ContentTemplate = TooltipTemplate
                                };
                                ToolTipService.SetToolTip(fe, tc);
                            }
                            batch.Panel.Children.Add(fe);
                        }
                        markersDrawn += batchSize;
                    }
                    batch.IsLayoutUpdated       = false;
                    batch.Image.Visibility      = System.Windows.Visibility.Collapsed;
                    batch.Image.RenderTransform = null;
                    batch.Panel.Visibility      = System.Windows.Visibility.Visible;
                    batch.Panel.InvalidateMeasure();
                    batch.PanelVersion = plotVersion;
                    batch.ClearChangedProperties();
                }
                finished = false;
            }
            if (finished)
            {
                idleTask.Stop();
                isDrawing = false;
                if (currentTaskId != -1)
                {
                    renderCompletion.OnNext(new MarkerGraphRenderCompletion(currentTaskId, markersDrawn));
                    currentTaskId = -1;
                }
            }
        }
コード例 #41
0
        private void WebsiteClick(object sender, MouseButtonEventArgs e)
        {
            ContentControl obj = sender as ContentControl;

            System.Diagnostics.Process.Start(obj.Content.ToString());
        }
コード例 #42
0
        private static PageBuilder CreatePage(object frameDataContext, Size paperSize, Margins margins)
        {
            var frame = new ContentControl();

            return(new PageBuilder(DPI * paperSize.Width, DPI * paperSize.Height, margins.Left, margins.Top, margins.Right, margins.Bottom, frame));
        }
コード例 #43
0
ファイル: TabContent.cs プロジェクト: Xden21/EAGLEMonitoring
 public static void SetInternalCachedContent(DependencyObject obj, ContentControl value)
 {
     obj.SetValue(InternalCachedContentProperty, value);
 }
コード例 #44
0
ファイル: NavigatorSupport.cs プロジェクト: alan008/Version3
        public static void InsertChemistry(bool isCopy, Application app, FlexDisplay flexDisplay)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Document       doc = app.ActiveDocument;
            Selection      sel = app.Selection;
            ContentControl cc  = null;

            if (Globals.Chem4WordV3.SystemOptions == null)
            {
                Globals.Chem4WordV3.LoadOptions();
            }

            bool   allowed = true;
            string reason  = "";

            if (Globals.Chem4WordV3.ChemistryAllowed)
            {
                if (sel.ContentControls.Count > 0)
                {
                    cc = sel.ContentControls[1];
                    if (cc.Title != null && cc.Title.Equals(Constants.ContentControlTitle))
                    {
                        reason  = "a chemistry object is selected";
                        allowed = false;
                    }
                }
            }
            else
            {
                reason  = Globals.Chem4WordV3.ChemistryProhibitedReason;
                allowed = false;
            }

            if (allowed)
            {
                app.ScreenUpdating = false;
                Globals.Chem4WordV3.DisableDocumentEvents(doc);

                try
                {
                    CMLConverter cmlConverter = new CMLConverter();
                    Model.Model  chem         = cmlConverter.Import(flexDisplay.Chemistry);
                    double       before       = chem.MeanBondLength;
                    if (before < Constants.MinimumBondLength - Constants.BondLengthTolerance ||
                        before > Constants.MaximumBondLength + Constants.BondLengthTolerance)
                    {
                        chem.ScaleToAverageBondLength(Constants.StandardBondLength);
                        double after = chem.MeanBondLength;
                        Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                    }

                    if (isCopy)
                    {
                        // Always generate new Guid on Import
                        chem.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                    }

                    string guidString   = chem.CustomXmlPartGuid;
                    string bookmarkName = "C4W_" + guidString;

                    if (Globals.Chem4WordV3.SystemOptions == null)
                    {
                        Globals.Chem4WordV3.LoadOptions();
                    }
                    Globals.Chem4WordV3.SystemOptions.WordTopLeft = Globals.Chem4WordV3.WordTopLeft;
                    IChem4WordRenderer renderer =
                        Globals.Chem4WordV3.GetRendererPlugIn(
                            Globals.Chem4WordV3.SystemOptions.SelectedRendererPlugIn);

                    if (renderer == null)
                    {
                        UserInteractions.WarnUser("Unable to find a Renderer Plug-In");
                    }
                    else
                    {
                        // Export just incase the CustomXmlPartGuid has been changed
                        string cml = cmlConverter.Export(chem);
                        renderer.Properties = new Dictionary <string, string>();
                        renderer.Properties.Add("Guid", guidString);
                        renderer.Cml = cml;

                        string tempfileName = renderer.Render();
                        if (File.Exists(tempfileName))
                        {
                            cc = CustomRibbon.Insert2D(doc, tempfileName, bookmarkName, guidString);

                            if (isCopy)
                            {
                                doc.CustomXMLParts.Add(cml);
                            }

                            try
                            {
                                // Delete the temporary file now we are finished with it
                                File.Delete(tempfileName);
                            }
                            catch
                            {
                                // Not much we can do here
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)
                    .ShowDialog();
                }
                finally
                {
                    // Tidy Up - Resume Screen Updating and Enable Document Event Handlers
                    app.ScreenUpdating = true;
                    Globals.Chem4WordV3.EnableDocumentEvents(doc);

                    if (cc != null)
                    {
                        // Move selection point into the Content Control which was just edited or added
                        app.Selection.SetRange(cc.Range.Start, cc.Range.End);
                    }
                }
            }
            else
            {
                UserInteractions.WarnUser($"You can't insert a chemistry object because {reason}");
            }
        }
コード例 #45
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="contentControl">The parent view to swap children in</param>
 public WpfPresenter(ContentControl contentControl)
 {
     _contentControl = contentControl;
 }
コード例 #46
0
        public void DisableEnable()
        {
            ContentControl c1 = new ContentControl();
            ContentControl c2 = new ContentControl();

            UIRegion.SetRegion(c1, "R1");
            UIRegion.SetRegion(c2, "R2");
            Manager.Register("R1", new Module("1", () => new VMTest()));
            Manager.Register("R1", new Module("2", () => new VMTest()));
            Manager.Register("R2", new Module("1", () => new VMTest()));
            Manager.Register("R2", new Module("2", () => new VMTest()));
            Manager.Inject("R1", "1");
            Manager.Inject("R1", "2");
            Manager.Inject("R2", "1");
            Manager.Inject("R2", "2");

            string logicalState = null;
            string visualState  = null;

            Manager.Save(out logicalState, out visualState);
            var logicalInfo = LogicalInfo.Deserialize(logicalState);
            var visualInfo  = VisualInfo.Deserialize(visualState);

            Assert.AreEqual(2, logicalInfo.Regions.Count());
            Assert.AreEqual("R1", logicalInfo.Regions[0].RegionName);
            Assert.AreEqual("R2", logicalInfo.Regions[1].RegionName);
            Assert.AreEqual(2, logicalInfo.Regions[0].Items.Count());
            Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count());

            Manager.GetRegion("R1").LogicalSerializationMode = LogicalSerializationMode.Disabled;
            Manager.Save(out logicalState, out visualState);
            logicalInfo = LogicalInfo.Deserialize(logicalState);
            visualInfo  = VisualInfo.Deserialize(visualState);
            Assert.AreEqual(2, logicalInfo.Regions.Count());
            Assert.AreEqual("R1", logicalInfo.Regions[0].RegionName);
            Assert.AreEqual("R2", logicalInfo.Regions[1].RegionName);
            Assert.AreEqual(0, logicalInfo.Regions[0].Items.Count());
            Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count());

            Manager.GetRegion("R1").LogicalSerializationMode = LogicalSerializationMode.Enabled;
            Manager.Save(out logicalState, out visualState);
            logicalInfo = LogicalInfo.Deserialize(logicalState);
            visualInfo  = VisualInfo.Deserialize(visualState);
            Assert.AreEqual(2, logicalInfo.Regions[0].Items.Count());
            Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count());

            Manager.GetRegion("R1").SetLogicalSerializationMode("1", LogicalSerializationMode.Disabled);
            Manager.Save(out logicalState, out visualState);
            logicalInfo = LogicalInfo.Deserialize(logicalState);
            visualInfo  = VisualInfo.Deserialize(visualState);
            Assert.AreEqual(1, logicalInfo.Regions[0].Items.Count());
            Assert.AreEqual("2", logicalInfo.Regions[0].Items[0].Key);
            Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count());

            Manager.GetRegion("R1").LogicalSerializationMode = LogicalSerializationMode.Disabled;
            Manager.GetRegion("R1").SetLogicalSerializationMode("2", LogicalSerializationMode.Enabled);
            Manager.Save(out logicalState, out visualState);
            logicalInfo = LogicalInfo.Deserialize(logicalState);
            visualInfo  = VisualInfo.Deserialize(visualState);
            Assert.AreEqual(1, logicalInfo.Regions[0].Items.Count());
            Assert.AreEqual("2", logicalInfo.Regions[0].Items[0].Key);
            Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count());

            Manager.GetRegion("R1").SetLogicalSerializationMode("1", null);
            Manager.GetRegion("R1").SetLogicalSerializationMode("2", null);
            Manager.Save(out logicalState, out visualState);
            logicalInfo = LogicalInfo.Deserialize(logicalState);
            visualInfo  = VisualInfo.Deserialize(visualState);
            Assert.AreEqual(0, logicalInfo.Regions[0].Items.Count());
            Assert.AreEqual(2, logicalInfo.Regions[1].Items.Count());
        }
コード例 #47
0
ファイル: Attached.cs プロジェクト: mijgame/Icons.Avalonia
 public static void SetIcon(ContentControl target, string value)
 {
     target.SetValue(IconProperty, value);
 }
コード例 #48
0
 internal ProfileDisplayModeTemplateSelector(ContentControl contentPresenter)
 {
     _contentPresenter = contentPresenter;
 }
コード例 #49
0
        override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            // objain require templated controls
            _contentControl = GetTemplateChild("FeatureDataField_ContentControl") as ContentControl;

            if (_contentControl != null)
            {
                _contentControl.GotFocus += ContentControl_GotFocus;
                _contentControl.LostFocus += ContentControl_LostFocus;                     
            }            

            // Render the UI.
            Refresh();
        }      
コード例 #50
0
 internal static void SetContentControl(UIElement element, ContentControl value)
 {
     element.SetValue(ContentControlProperty, value);
 }
コード例 #51
0
        public void GetVisualParents2() {
            Grid grid = new Grid();
            ContentControl contentControl = new ContentControl();
            TextBlock textBox;
            System.Windows.Documents.Inline textBoxContent = null;
            Window.Content = grid;
            grid.Children.Add(contentControl);
            contentControl.ContentTemplate = textBlockTemplate;
            EnqueueShowWindow();
            EnqueueCallback(() => {
                textBox = (TextBlock)LayoutHelper.FindElement(contentControl, x => x is TextBlock);
                textBoxContent = textBox.Inlines.First();

                Assert.AreSame(contentControl, LayoutTreeHelper.GetVisualParents(textBoxContent).Where(x => x is ContentControl).First());
                Assert.AreSame(grid, LayoutTreeHelper.GetVisualParents(textBoxContent).Where(x => x is Grid).First());
                Assert.AreSame(Window, LayoutTreeHelper.GetVisualParents(textBoxContent).Where(x => x.GetType() == Window.GetType()).First());

                Assert.AreSame(contentControl, LayoutTreeHelper.GetVisualParents(textBoxContent, contentControl).Where(x => x is ContentControl).First());
                Assert.IsNull(LayoutTreeHelper.GetVisualParents(textBoxContent, contentControl).Where(x => x is Grid).FirstOrDefault());
            });
            EnqueueTestComplete();
        }
コード例 #52
0
 public BaseEquipMentContent(ContentControl contentControl, GameObject baseEquipment)
 {
     this.contentControl = contentControl;
     this.baseEquipment  = baseEquipment;
     this.baseEquipment.SetActive(false);
 }
コード例 #53
0
        internal ContentModelTreeEnumerator(ContentControl contentControl, object content) : base(content)
        {
            Debug.Assert(contentControl != null, "contentControl should be non-null.");

            _owner = contentControl;
        }
コード例 #54
0
        private void LoadTab(ContentControl tab, int page)
        {
            var scroll = new ScrollViewer {
                Name = "ScrollContent", Margin = new Thickness(10), VerticalAlignment = VerticalAlignment.Top
            };

            var holder = new WrapPanel {
                Margin = new Thickness(0), VerticalAlignment = VerticalAlignment.Top
            };

            // setup grid
            var grid = this.GenerateTabGrid();

            var x    = 1;
            var list = this.items.Where(i => i.Page == page).OrderByDescending(i => i.BaseAddress);

            if (page == 4)
            {
                list = this.items.Where(i => i.Page == 4 || i.Page == 5 || i.Page == 6).OrderByDescending(i => i.BaseAddress);
            }

            foreach (var item in list)
            {
                grid.RowDefinitions.Add(new RowDefinition());

                var value = item.Value;
                if (value > int.MaxValue)
                {
                    value = 0;
                }

                // Name
                var name = new TextBox
                {
                    Text    = item.Name,
                    ToolTip = BitConverter.ToString(Encoding.Default.GetBytes(item.Name)).Replace("-", string.Empty),
                    //ToolTip = item.Address.ToString("x8").ToUpper(),
                    Margin          = new Thickness(0, 0, 10, 0),
                    Height          = 22,
                    Width           = 250,
                    IsReadOnly      = true,
                    BorderThickness = new Thickness(0)
                };

                Grid.SetRow(name, x);
                Grid.SetColumn(name, 0);
                grid.Children.Add(name);

                // Value
                var val = this.GenerateGridTextBox(value.ToString(), item.BaseAddressHex, x, 1);
                val.PreviewTextInput += this.NumberValidationTextBox;
                grid.Children.Add(val);

                // Mod1
                var mtb1 = this.GenerateGridTextBox(item.Modifier1Value, item.Modifier1Address, x, 2);
                grid.Children.Add(mtb1);

                // Mod2
                var mtb2 = this.GenerateGridTextBox(item.Modifier2Value, item.Modifier2Address, x, 3);
                grid.Children.Add(mtb2);

                // Mod3
                var mtb3 = this.GenerateGridTextBox(item.Modifier3Value, item.Modifier3Address, x, 4);
                grid.Children.Add(mtb3);

                // Mod4
                var mtb4 = this.GenerateGridTextBox(item.Modifier4Value, item.Modifier4Address, x, 5);
                grid.Children.Add(mtb4);

                // Mod5
                var mtb5 = this.GenerateGridTextBox(item.Modifier5Value, item.Modifier5Address, x, 6);
                grid.Children.Add(mtb5);

                x++;
            }

            grid.Height = x * 35;

            if (tab.Name == "Food")
            {
                holder.Children.Add(new TextBox
                {
                    Background      = Brushes.Transparent,
                    BorderThickness = new Thickness(0),
                    Margin          = new Thickness(10, 10, 0, 0),
                    IsReadOnly      = true,
                    TextWrapping    = TextWrapping.Wrap,
                    Text            = "See post: https://gbatemp.net/threads/post-your-wiiu-cheat-codes-here.395443/page-303#post-7156278"
                });
            }

            holder.Children.Add(grid);

            scroll.Content = holder;

            tab.Content = scroll;
        }
コード例 #55
0
        public void SelectedItemBinding()
        {
            OverriddenAutoCompleteBox acb = new OverriddenAutoCompleteBox();
            acb.ItemsSource = "words go here".Split();
            ContentControl cc = new ContentControl();
            Binding b = new Binding("SelectedItem");
            b.Source = acb;
            cc.SetBinding(ContentControl.ContentProperty, b);

            int loadedCount = 0;
            acb.Loaded += (o, e) => loadedCount++;
            cc.Loaded += (o, e) => loadedCount++;

            EnqueueCallback(() => TestPanel.Children.Add(acb));
            EnqueueCallback(() => TestPanel.Children.Add(cc));
            EnqueueConditional(() => 2 == loadedCount);

            EnqueueCallback(() => acb.TextBox.Text = "w");
            EnqueueConditional(() => acb.IsDropDownOpen);

            EnqueueCallback(() => OverriddenSelectionAdapter.Current.SelectFirst());
            EnqueueCallback(() => Assert.AreEqual("words", acb.SelectedItem));

            EnqueueCallback(() => OverriddenSelectionAdapter.Current.TestCommit());
            EnqueueConditional(() => !acb.IsDropDownOpen);

            EnqueueCallback(() => Assert.AreEqual("words", cc.Content));

            EnqueueTestComplete();
        }
コード例 #56
0
 /// <summary>
 /// Set the Margin for a ContentControl
 /// </summary>
 /// <param name="dataColumn"></param>
 /// <param name="uiElement"></param>
 /// <param name="dataContext"></param>
 public override void OnInitializeDisplayElement(DataColumnBase dataColumn, ContentControl uiElement, object dataContext)
 {
     base.OnInitializeDisplayElement(dataColumn, uiElement, dataContext);
     uiElement.Margin = new Thickness(5, 0, 0, 0);
 }
コード例 #57
0
        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"));
        }
コード例 #58
0
        public void CanReuseElementsDuringUniqueIdReset()
        {
            var data = new WinRTCollection(Enumerable.Range(0, 2).Select(i => string.Format("Item #{0}", i)));
            List <UIElement>   mapping        = null;
            ItemsRepeater      repeater       = null;
            MockElementFactory elementFactory = null;
            ContentControl     focusedElement = null;

            RunOnUIThread.Execute(() =>
            {
                mapping = new List <UIElement> {
                    new ContentControl(), new ContentControl()
                };
                repeater = CreateRepeater(
                    MockItemsSource.CreateDataSource(data, supportsUniqueIds: true),
                    MockElementFactory.CreateElementFactory(mapping));
                elementFactory = (MockElementFactory)repeater.ItemTemplate;

                Content = repeater;
                repeater.UpdateLayout();

                focusedElement = (ContentControl)repeater.TryGetElement(1);
                focusedElement.Focus(FocusState.Keyboard);
            });
            IdleSynchronizer.Wait();

            RunOnUIThread.Execute(() =>
            {
                elementFactory.ValidateGetElementCalls(
                    new MockElementFactory.GetElementCallInfo(0, repeater),
                    new MockElementFactory.GetElementCallInfo(1, repeater));
                elementFactory.ValidateRecycleElementCalls();

                data.ResetWith(new[] { data[0], "New item" });

                Verify.AreEqual(0, repeater.GetElementIndex(mapping[0]));
                Verify.AreEqual(1, repeater.GetElementIndex(mapping[1]));
                Verify.IsNull(repeater.TryGetElement(0));
                Verify.IsNull(repeater.TryGetElement(1));

                elementFactory.ValidateGetElementCalls(/* GetElement should not be called */);
                elementFactory.ValidateRecycleElementCalls(/* RecycleElement should not be called */);

                mapping[1] = new ContentControl(); // For "New Item"

                repeater.UpdateLayout();

                Verify.AreEqual(0, repeater.GetElementIndex(mapping[0]));
                Verify.AreEqual(1, repeater.GetElementIndex(mapping[1]));
                Verify.AreEqual(mapping[0], repeater.TryGetElement(0));
                Verify.AreEqual(mapping[1], repeater.TryGetElement(1));

                elementFactory.ValidateGetElementCalls(
                    new MockElementFactory.GetElementCallInfo(1, repeater));
                elementFactory.ValidateRecycleElementCalls(
                    new MockElementFactory.RecycleElementCallInfo(focusedElement, repeater));

                // If the focused element survived the reset, we will keep focus on it. If not, we
                // try to find one based on the index. In this case, the focused element (index 1)
                // got recycled, and we still have index 1 after the stable reset, so the new index 1
                // will get focused. Note that recycling the elements to view generator in the case of
                // stable reset happens during the arrange, so by that time we will have pulled elements
                // from the stable reset pool and maybe created some new elements as well.
                int index = repeater.GetElementIndex(focusedElement);
                Log.Comment("focused index " + index);
                Verify.AreEqual(mapping[1], FocusManager.GetFocusedElement());
            });
        }
コード例 #59
0
        public void Should_Raise_DetachedFromLogicalTree_In_ContentControl_On_Content_Changed_OutsideTemplate()
        {
            var contentControl = new ContentControl
            {
                Template = new FuncControlTemplate<ContentControl>(c => new ContentPresenter()
                {
                    Name = "PART_ContentPresenter",
                    [~ContentPresenter.ContentProperty] = c[~ContentControl.ContentProperty],
                    [~ContentPresenter.ContentTemplateProperty] = c[~ContentControl.ContentTemplateProperty]
                }),
                ContentTemplate =
                    new FuncDataTemplate<string>(t => new ContentControl() { Content = t }, false)
            };

            var parentMock = new Mock<Control>();
            parentMock.As<IStyleRoot>();
            parentMock.As<ILogical>().SetupGet(l => l.IsAttachedToLogicalTree).Returns(true);

            (contentControl as ISetLogicalParent).SetParent(parentMock.Object);

            contentControl.ApplyTemplate();
            var target = contentControl.Presenter as ContentPresenter;

            contentControl.Content = "foo";

            target.UpdateChild();

            var tbfoo = target.Child as ContentControl;

            bool foodetached = false;

            Assert.NotNull(tbfoo);
            Assert.Equal("foo", tbfoo.Content);

            tbfoo.DetachedFromLogicalTree += delegate { foodetached = true; };

            contentControl.Content = "bar";
            target.UpdateChild();

            var tbbar = target.Child as ContentControl;

            Assert.NotNull(tbbar);
            Assert.True(tbbar != tbfoo);
            Assert.False((tbfoo as IControl).IsAttachedToLogicalTree);
            Assert.True(foodetached);
        }
コード例 #60
0
 public IPluginViewSettings Add2DPropertyView(ContentControl hostControl)
 {
     return(null);
 }