Ejemplo n.º 1
0
        protected void UpdateView()
        {
            var scrollViewer = this.GetTemplateChild("PART_ContentHost") as ScrollViewer;
            var whenFocused = scrollViewer?.NestedChildren().OfType<ScrollContentPresenter>().SingleOrDefault();
            var grid = whenFocused?.Parent as Grid;
            if (scrollViewer == null || whenFocused == null || grid == null)
            {
                if (!this.IsLoaded)
                {
                    this.Loaded += OnLoaded;
                    return;
                }

                if (this.IsArrangeValid == false)
                {
                    // retry after arrange
                    // using the Loaded event does not work if template is changed in runtime.
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(this.UpdateView));
                    return;
                }

                if (DesignerProperties.GetIsInDesignMode(this))
                {
                    var message = $"The template does not match the expected template. Cannot use formatting\r\n" +
                                  $"The expected template is (pseudo)\r\n" +
                                  $"{nameof(ScrollViewer)}: {(scrollViewer == null ? "null" : string.Empty)}\r\n" +
                                  $"  {nameof(Grid)}: {(grid == null ? "null" : string.Empty)}\r\n" +
                                  $"    {nameof(ScrollContentPresenter)}: {(whenFocused == null ? "null" : string.Empty)}";
                    throw new InvalidOperationException(message);
                }
                else
                {
                    // Falling back to vanilla textbox in runtime
                    return;
                }
            }

            var formattedBox = (TextBlock)grid.FindName(FormattedName);
            if (formattedBox == null)
            {
                var whenNotFocused = new TextBlock
                {
                    Name = FormattedName,
                    VerticalAlignment = VerticalAlignment.Center
                };

                whenNotFocused.Bind(TextBlock.TextProperty)
                    .OneWayTo(this, FormattedTextProperty);

                whenNotFocused.Bind(MarginProperty)
                    .OneWayTo(whenFocused, MarginProperty, FormattedTextBlockMarginConverter.Default, whenFocused);

                whenNotFocused.Bind(VisibilityProperty)
                    .OneWayTo(this, IsKeyboardFocusWithinProperty, HiddenWhenTrueConverter.Default);

                grid.Children.Add(whenNotFocused);

                whenFocused.Bind(VisibilityProperty)
                    .OneWayTo(this, IsKeyboardFocusWithinProperty, VisibleWhenTrueConverter.Default);
            }
        }