Example #1
0
        public static object GetObject(string caseString, Type genericType)
        {
            object result;

            if (!genericType.IsValueType && caseString == FlowSwitchNullCaseKeyIdentifier)
            {
                result = null;
            }
            else if (typeof(string).IsAssignableFrom(genericType))
            {
                if (caseString == FlowSwitchEmptyCaseKeyIdentifier)
                {
                    result = string.Empty;
                }
                else
                {
                    result = caseString;
                }
            }
            else
            {
                //If target type is value type and the caseString is null, we should leave converter to process it.
                //If target type is reference type, the caseString is a non-null value here.
                result = XamlUtilities.GetConverter(genericType).ConvertFromString(caseString);
            }
            return(result);
        }
Example #2
0
        public static FrameworkElement Render(AdaptiveTimeInput input, AdaptiveRenderContext context)
        {
            if (!context.Config.SupportsInteractivity)
            {
                AdaptiveTextBlock textBlock = AdaptiveTypedElementConverter.CreateElement <AdaptiveTextBlock>();
                textBlock.Text = XamlUtilities.GetFallbackText(input) ?? input.Placeholder;

                return(context.Render(textBlock));
            }

            TimePicker timePicker = new TimePicker
            {
                DataContext = input,
                ToolTip     = input.Placeholder,
                Style       = context.GetStyle("Adaptive.Input.Time"),
                Is24Hours   = true
            };

            if (DateTime.TryParse(input.Value, out DateTime value))
            {
                timePicker.SelectedTime = value;
            }

            context.InputBindings.Add(input.Id, () => timePicker.SelectedTime?.ToString("HH:mm") ?? "");

            return(timePicker);
        }
Example #3
0
        object IMultiValueConverter.Convert(
            object[] values,
            Type targetType,
            object parameter,
            CultureInfo cultureInfo)
        {
            var arg1 = XamlUtilities.Convert <T1>(values[0], this);

            var arg2 = XamlUtilities.Convert <T2>(values[1], this);

            var arg3 = XamlUtilities.Convert <T3>(values[2], this);

            var arg4 = XamlUtilities.Convert <T4>(values[3], this);

            var arg5 = XamlUtilities.Convert <T5>(values[4], this);


            var param = XamlUtilities.ConvertParam <TParam>(
                parameter, cultureInfo, this);

            return(Convert(
                       arg1,
                       arg2,
                       arg3,
                       arg4,
                       arg5,
                       (TParam)param));
        }
        internal static string GetExpressionString(Activity expression, ParserContext context)
        {
            string expressionString = null;

            if (expression != null)
            {
                Type expressionType         = expression.GetType();
                Type expressionArgumentType = expressionType.IsGenericType ? expressionType.GetGenericArguments()[0] : typeof(object);
                bool isLiteral = expressionType.IsGenericType ? Type.Equals(typeof(Literal <>), expressionType.GetGenericTypeDefinition()) : false;

                //handle ITextExpression
                if (expression is ITextExpression)
                {
                    ITextExpression textExpression = expression as ITextExpression;
                    expressionString = textExpression.ExpressionText;
                }
                //handle Literal Expression
                else if (isLiteral)
                {
                    TypeConverter converter = XamlUtilities.GetConverter(expressionArgumentType);
                    if (converter != null && converter.CanConvertTo(context, typeof(string)))
                    {
                        PropertyInfo literalValueProperty = expressionType.GetProperty("Value");
                        Fx.Assert(literalValueProperty != null && literalValueProperty.GetGetMethod() != null, "Literal<T> must have the Value property with a public get accessor.");
                        object literalValue    = literalValueProperty.GetValue(expression, null);
                        string convertedString = null;
                        if (literalValue != null)
                        {
                            try
                            {
                                convertedString = converter.ConvertToString(context, literalValue);
                            }
                            catch (ArgumentException)
                            {
                                convertedString = literalValue.ToString();
                            }
                        }
                        expressionString = expressionArgumentType == typeof(string) ? ("\"" + convertedString + "\"") : convertedString;
                    }
                }
                else if (expressionType.IsGenericType &&
                         (expressionType.GetGenericTypeDefinition() == typeof(VariableValue <>) ||
                          expressionType.GetGenericTypeDefinition() == typeof(VariableReference <>)))
                {
                    PropertyInfo variableProperty = expression.GetType().GetProperty("Variable");
                    Variable     variable         = variableProperty.GetValue(expression, null) as Variable;
                    if (variable != null)
                    {
                        expressionString = variable.Name;
                    }
                }
            }

            return(expressionString);
        }
        private void SetupBackButton()
        {
            var children = XamlUtilities.RecurseChildren(ShellView);
            var grids    = children.OfType <Grid>();
            var grid     = grids.Single(x => x.Name == "TogglePaneTopPadding");

            grid.Visibility = Visibility.Collapsed;

            grid = grids.Single(x => x.Name == "ContentPaneTopPadding");
            grid.RegisterPropertyChangedCallback(HeightProperty, (s, args) =>
            {
                if (grid.Height != 44d)
                {
                    grid.Height = 44d;
                }
            });
            grid.Height = 44d;

            var buttons = children.OfType <Button>();
            var button  = buttons.Single(x => x.Name == "TogglePaneButton");

            button.RegisterPropertyChangedCallback(MarginProperty, (s, args) =>
            {
                if (button.Margin.Top != 0)
                {
                    button.Margin = new Thickness(0, 0, 0, 32);
                }
            });
            button.Margin = new Thickness(0, 0, 0, 32);
            button.Focus(FocusState.Programmatic);

            var parent     = button.Parent as Grid;
            var backButton = new Button
            {
                Name    = "BackButton",
                Content = new SymbolIcon
                {
                    Symbol           = Symbol.Back,
                    IsHitTestVisible = false
                },
                Style = Resources["PaneToggleButtonStyle"] as Style,
            };

            parent.Children.Insert(1, backButton);
            ShellView.NavigationService.CanGoBackChanged += (s, args) =>
            {
                backButton.IsEnabled = ShellView.NavigationService.CanGoBack();
            };
            backButton.Click += (s, args) =>
            {
                _gestureService.RaiseBackRequested();
            };
        }
        public void OnValueChanged()
        {
            if (this.Value is ModelItem)
            {
                // Since Value is a DP, this code will trigger OnValueChanged once more.
                this.Value = ((ModelItem)this.Value).GetCurrentValue();
                return;
            }

            if (this.DataTemplateName != LabelTemplate && !this.IsBoxOnly)
            {
                this.DataTemplateName = LabelTemplate;
            }

            if (this.DisplayHintText)
            {
                this.Text = string.Empty;
                return;
            }
            if (this.ValueType == null)
            {
                return;
            }
            if (this.ValueType.IsValueType)
            {
                if (this.Value == null)
                {
                    this.Value = Activator.CreateInstance(this.ValueType);
                }
            }
            if (this.Value == null)
            {
                this.Text = Null;
            }
            else if ((this.ValueType == typeof(string)) && string.Equals(this.Value, String.Empty))
            {
                this.Text = Empty;
            }
            else
            {
                TypeConverter converter = XamlUtilities.GetConverter(this.ValueType);
                Fx.Assert(converter != null, "TypeConverter is not available");
                try
                {
                    this.Text = converter.ConvertToString(this.Value);
                }
                catch (ArgumentException)
                {
                    this.Text = this.Value.ToString();
                }
            }
        }
Example #7
0
        object IValueConverter.Convert(
            object value,
            Type targetType,
            object parameter,
            CultureInfo cultureInfo)
        {
            var arg1 = XamlUtilities.Convert <T1>(value, this);

            var param = XamlUtilities.ConvertParam <TParam>(
                parameter, cultureInfo, this);

            return(Convert(arg1, (TParam)param));
        }
        object ResolveInputText()
        {
            object result = null;

            if (this.ValueType == typeof(string))
            {
                if (this.Text.Equals(Null))
                {
                    result = null;
                }
                else if (this.Text.Equals(Empty))
                {
                    result = string.Empty;
                }
                else
                {
                    result = this.Text;
                }
            }
            else if (!this.ValueType.IsValueType && this.Text.Equals(Null))
            {
                result = null;
            }
            else
            {
                TypeConverter converter = XamlUtilities.GetConverter(this.ValueType);
                Fx.Assert(converter != null, "TypeConverter is not available");

                if (!converter.CanConvertFrom(typeof(string)) || !converter.CanConvertTo(typeof(string)))
                {
                    throw FxTrace.Exception.AsError(new NotSupportedException(SR.NotSupportedCaseKeyStringConversion));
                }

                result = converter.ConvertFromString(this.Text);
                // See if the result can be converted back to a string.
                // For example, we have a enum Color {Black, White}.
                // String "3" can be converted to integer 3, but integer 3
                // cannot be converted back to a valid string for enum Color.
                // In this case, we disallow string "3".
                converter.ConvertToString(result);
            }

            string reason;

            if (this.CaseKeyValidationCallback != null && !this.CaseKeyValidationCallback(result, out reason))
            {
                throw FxTrace.Exception.AsError(new ArgumentException(reason));
            }

            return(result);
        }
        public void InstallHyperLinkerNavgiateEvent_Tests()
        {
            int eventFired = 0;
            FrameworkElement testElement = XamlUtilities.GetElementFromString(ValidXamlWithHyperlink);

            testElement.Should().NotBeNull();
            XamlUtilities.InstallHyperLinkerNavgiateEvent(testElement, delegate { eventFired++; });

            var stackPanel = LogicalTreeHelper.GetChildren(testElement).Cast <object>().First() as StackPanel;
            var textBlock  = LogicalTreeHelper.GetChildren(stackPanel).Cast <object>().First() as TextBlock;
            var hyperlink  = LogicalTreeHelper.GetChildren(textBlock).Cast <object>().First() as Hyperlink;

            hyperlink.Should().NotBeNull();

            eventFired.Should().Be(0);
            hyperlink.RaiseEvent(new RequestNavigateEventArgs(hyperlink.NavigateUri, hyperlink.TargetName));
            eventFired.Should().Be(1);
        }
Example #10
0
        //Raw string means the null is not represented as "<null>" and string.Empty is not represented as "<empty>".
        static string GetRawString(object caseObject)
        {
            string result = null;

            if (caseObject == null)
            {
                return(null);
            }
            if (!(caseObject is string))
            {
                result = XamlUtilities.GetConverter(caseObject.GetType()).ConvertToString(caseObject);
            }
            else
            {
                result = (string)caseObject;
            }
            return(result);
        }
        public void CreateScrollViewElement_Tests()
        {
            SarifViewerPackage.IsUnitTesting = true;

            FrameworkElement testElement = XamlUtilities.GetElementFromString(ValidXamlWithHyperlink);

            testElement.Should().NotBeNull();

            FrameworkElement scrollViewerElement = XamlUtilities.CreateScrollViewElement(testElement);

            scrollViewerElement.Should().NotBeNull();

            ScrollViewer scrollViewer = scrollViewerElement as ScrollViewer;

            scrollViewer.Should().NotBeNull();

            scrollViewer.Content.Should().Be(testElement);
            scrollViewer.VerticalScrollBarVisibility.Should().Be(ScrollBarVisibility.Auto);
            scrollViewer.MaxHeight.Should().Be(XamlUtilities.ScrollViewerMaxHeight);
        }
        public void GetElementFromString_Tests()
        {
            XamlUtilities.GetElementFromString(null).Should().BeNull();
            XamlUtilities.GetElementFromString(string.Empty).Should().BeNull();
            XamlUtilities.GetElementFromString("          ").Should().BeNull();
            XamlUtilities.GetElementFromString("The quick brown fox jumps over the lazy dog").Should().BeNull();
            XamlUtilities.GetElementFromString("<The quick brown> <fox> <jumps over the lazy dog>").Should().BeNull();
            XamlUtilities.GetElementFromString(InvalidXaml).Should().BeNull();

            FrameworkElement testElement = XamlUtilities.GetElementFromString(ValidXamlWithHyperlink);

            testElement.Should().NotBeNull();

            var stackPanel = LogicalTreeHelper.GetChildren(testElement).Cast <object>().First() as StackPanel;

            stackPanel.Should().NotBeNull();
            var textBlock = LogicalTreeHelper.GetChildren(stackPanel).Cast <object>().First() as TextBlock;

            textBlock.Should().NotBeNull();
            var hyperlink = LogicalTreeHelper.GetChildren(textBlock).Cast <object>().First() as Hyperlink;

            hyperlink.Should().NotBeNull();
        }
Example #13
0
        public static FrameworkElement Render(AdaptiveDateInput input, AdaptiveRenderContext context)
        {
            if (!context.Config.SupportsInteractivity)
            {
                AdaptiveTextBlock textBlock = AdaptiveTypedElementConverter.CreateElement <AdaptiveTextBlock>();
                textBlock.Text = XamlUtilities.GetFallbackText(input) ?? input.Placeholder;

                return(context.Render(textBlock));
            }

            DatePicker datePicker = new DatePicker
            {
                DataContext = input,
                ToolTip     = input.Placeholder,
                Style       = context.GetStyle("Adaptive.Input.Date")
            };


            if (DateTime.TryParse(input.Value, out DateTime value))
            {
                datePicker.SelectedDate = value;
            }

            if (DateTime.TryParse(input.Min, out DateTime minValue))
            {
                datePicker.DisplayDateStart = minValue;
            }

            if (DateTime.TryParse(input.Max, out DateTime maxValue))
            {
                datePicker.DisplayDateEnd = maxValue;
            }

            context.InputBindings.Add(input.Id, () => datePicker.SelectedDate?.ToString("yyyy-MM-dd") ?? "");

            return(datePicker);
        }
Example #14
0
        private void SetupBackButton()
        {
            var children = XamlUtilities.RecurseChildren(this);
            var grids    = children.OfType <Grid>();
            var grid     = grids.Single(x => x.Name == "TogglePaneTopPadding");

            grid.Visibility = Visibility.Collapsed;

            grid = grids.Single(x => x.Name == "ContentPaneTopPadding");
            grid.RegisterPropertyChangedCallback(HeightProperty, (s, args) =>
            {
                if (grid.Height != 44d)
                {
                    grid.Height = 44d;
                }
            });
            grid.Height = 44d;

            var child_buttons = children.OfType <Button>();

            _togglePaneButton = child_buttons.Single(x => x.Name == "TogglePaneButton");
            _togglePaneButton.RegisterPropertyChangedCallback(MarginProperty, (s, args) =>
            {
                if (_togglePaneButton.Margin.Top != 0)
                {
                    _togglePaneButton.Margin = new Thickness(0, 0, 0, 32);
                }
            });
            _togglePaneButton.Margin = new Thickness(0, 0, 0, 32);
            _togglePaneButton.Focus(FocusState.Programmatic);

            var parent_grid = _togglePaneButton.Parent as Grid;

            parent_grid.Width = double.NaN;
            parent_grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(48)
            });
            parent_grid.ColumnDefinitions.Add(new ColumnDefinition {
            });
            parent_grid.RowDefinitions[0].Height = GridLength.Auto;
            parent_grid.RowDefinitions[1].Height = GridLength.Auto;

            _paneTitleTextBlock = new TextBlock
            {
                Name              = "PaneTitleTextBlock",
                Margin            = new Thickness(8, 18, 0, 0),
                FontSize          = 15,
                FontFamily        = new FontFamily("Segoe UI Bold"),
                TextWrapping      = TextWrapping.NoWrap,
                Foreground        = Resources["SystemControlForegroundBaseHighBrush"] as Brush,
                VerticalAlignment = VerticalAlignment.Top,
                IsHitTestVisible  = false,
                Text              = "Jerry Nixon",
            };
            _paneTitleTextBlock.SetValue(Grid.ColumnProperty, 1);
            _paneTitleTextBlock.SetValue(Grid.RowProperty, 1);
            _paneTitleTextBlock.SetValue(Canvas.ZIndexProperty, 100);
            // parent_grid.Children.Add(_paneTitleTextBlock);

            _backButton = new Button
            {
                Name    = "BackButton",
                Content = new SymbolIcon
                {
                    Symbol           = Symbol.Back,
                    IsHitTestVisible = false
                },
                Style = Resources["PaneToggleButtonStyle"] as Style,
            };
            _backButton.SetValue(Canvas.ZIndexProperty, 100);
            parent_grid.Children.Insert(1, _backButton);

            NavigationService.CanGoBackChanged += (s, args) =>
            {
                _backButton.IsEnabled = NavigationService.CanGoBack();
            };

            _backButton.Click += (s, args) =>
            {
                var gesture_service = GestureService.GetForCurrentView();
                gesture_service.RaiseBackRequested();
            };
        }
Example #15
0
        private void UpdatePageHeaderContent()
        {
            _updatePageHeaderSemaphore.Wait();

            try
            {
                if (_frame.Content is Page page)
                {
                    if (page.GetValue(NavProperties.HeaderProperty) is string headerText && !Equals(Header, headerText))
                    {
                        Header = headerText;
                    }


                    if (!(page.GetValue(NavProperties.HeaderCommandsProperty) is ObservableCollection <object> headerCommands) || !(headerCommands.Any()))
                    {
                        localClearPageHeaderCommands();
                    }
                    else
                    {
                        localUpdatePageHeaderCommands(headerCommands);
                    }
                }
            }
            finally
            {
                _updatePageHeaderSemaphore.Release();
            }

            #region local functions

            void localClearPageHeaderCommands()
            {
                if (!localTryGetCommandBar(out var bar))
                {
                    return;
                }

                bar.PrimaryCommands.Clear();
            }

            bool localTryGetCommandBar(out CommandBar bar)
            {
                var children = XamlUtilities.RecurseChildren(this);
                var bars     = children
                               .OfType <CommandBar>();

                if (!bars.Any())
                {
                    bar = default(CommandBar);
                    return(false);
                }
                bar = bars.First();
                return(true);
            }

            void localUpdatePageHeaderCommands(ObservableCollection <object> headerCommands)
            {
                if (!localTryGetCommandBar(out var bar))
                {
                    return;
                }

                var previous = bar.PrimaryCommands
                               .OfType <DependencyObject>()
                               .Where(x => x.GetValue(NavProperties.PageHeaderCommandDynamicItemProperty) is bool value && value);

                foreach (var command in previous.OfType <ICommandBarElement>().ToArray())
                {
                    bar.PrimaryCommands.Remove(command);
                }

                foreach (var command in headerCommands.Reverse().OfType <DependencyObject>().ToArray())
                {
                    command.SetValue(NavProperties.PageHeaderCommandDynamicItemProperty, true);
                    bar.PrimaryCommands.Insert(0, command as ICommandBarElement);
                }
            }

            #endregion
        }