예제 #1
0
 public FormsLayoutInfo(UIElementCollection children, Size size, int breakOnItem, double splitWidth)
 {
     Children = children;
     Size = size;
     BreakOnItem = breakOnItem;
     SplitWidth = splitWidth;
 }
예제 #2
0
 private double MeasureChildren(UIElementCollection children, int start, int to, Size childSize)
 {
     var currentHeight = 0.0;
     for (int i = start; i < to; i++)
     {
         var child = children[i];
         child.Measure(childSize);
         currentHeight += child.DesiredSize.Height;
     }
     return currentHeight;
 }
예제 #3
0
 public static void DeleteFromCollection(UIElementCollection extensions, Guid extGuid)
 {
     foreach (dynamic child in extensions)
     {
         if (child is IExtension)
         {
             if (((Guid)child.ExtensionManifest.UniqueID).ToString() == extGuid.ToString())
             {
                 X.Services.Extensions.ExtensionsService.Instance.UninstallInstance((Guid)child.ExtensionManifest.UniqueID);
                 extensions.Remove(child);
                 break;
             }
         }
     }
 }
예제 #4
0
        public HullEditor()
        {
            _elementCollection = new UIElementCollection();
            UIElementCollection.BindCollection(_elementCollection);

            _sidepanel = new SideEditorPanel(0, 0, ScreenData.GetScreenValueX(0.5f), ScreenData.GetScreenValueY(0.5f), "save/side.xml");
            _toppanel = new TopEditorPanel(0, ScreenData.GetScreenValueY(0.5f), ScreenData.GetScreenValueX(0.5f), ScreenData.GetScreenValueY(0.5f), "save/top.xml");
            _backpanel = new BackEditorPanel(ScreenData.GetScreenValueX(0.5f), 0, ScreenData.GetScreenValueX(0.25f), ScreenData.GetScreenValueY(0.5f), "save/back.xml");

            _sidepanel.BackPanel = _backpanel;
            _sidepanel.TopPanel = _toppanel;

            _toppanel.BackPanel = _backpanel;
            _toppanel.SidePanel = _sidepanel;

            _backpanel.TopPanel = _toppanel;
            _backpanel.SidePanel = _sidepanel;

            _previewRenderer = new PreviewRenderer(_sidepanel.Curves, _toppanel.Curves, _backpanel.Curves);

            UIElementCollection.UnbindCollection();
        }
예제 #5
0
        public DoodadEditor(List<BezierInfo> backCurveInfo, List<BezierInfo> sideCurveInfo, List<BezierInfo> topCurveInfo)
        {
            _renderTarget = new RenderPanel(0, 0, ScreenData.ScreenWidth, ScreenData.ScreenHeight);
            _uiElementCollection = new UIElementCollection();
            _cameraController = new BodyCenteredCamera();

            #region construct UI and any UI-related tools

            RenderPanel.BindRenderTarget(_renderTarget);
            UIElementCollection.BindCollection(_uiElementCollection);

            var geometryInfo = HullGeometryGenerator.GenerateShip(backCurveInfo, sideCurveInfo, topCurveInfo, _primsPerDeck);
            _hullData = new HullDataManager(geometryInfo);

            _doodadUI = new DoodadUI(_hullData);

            RenderPanel.UnbindRenderTarget();
            UIElementCollection.UnbindCollection();

            #endregion

            _cameraController.SetCameraTarget(_hullData.CenterPoint);
        }
예제 #6
0
        public string getSelected(GroupBox grpBox)
        {
            string res = "None - Vide";
            //   Grid grd = (Grid)grpBox.Content;
            UIElementCollection uiec = panelA.Children;

            foreach (UIElement uelement in uiec)
            {
                if (typeof(RadioButton) == uelement.GetType())
                {
                    RadioButton rbtn = (RadioButton)uelement;
                    if ((bool)rbtn.IsChecked)
                    {
                        cb.SelectedItem = null;
                        res             = rbtn.Content.ToString();
                    }
                }
            }
            uiec = panelB.Children;
            foreach (UIElement uelement in uiec)
            {
                if (typeof(RadioButton) == uelement.GetType())
                {
                    RadioButton rbtn = (RadioButton)uelement;
                    if ((bool)rbtn.IsChecked)
                    {
                        cb.SelectedItem = null;
                        res             = rbtn.Content.ToString();
                    }
                }
            }

            if (cb.SelectedItem != null)
            {
                res = "_TypesPayDynamic" + (cb.SelectedItem as ClassSync.TypesPayDB).Id;
            }

            if (xDescription.Text.TrimEnd() != "")
            {
                List <Class.ClassProducts.product> lp = Class.ClassProducts.getProduct(xDescription.Text);

                switch (lp.Count)
                {
                case 0: statusMes.Content = ("С таким именем продукт не найден "); this.xtbc.SelectedIndex = 3; _expander.IsExpanded = true; break;

                case 1: statusMes.Content = (""); res = "Products id=[" + lp[0].CustumerId.ToString() + "]"; break;

                default:
                    Class.ClassProducts.product pe = list.SelectedItem as Class.ClassProducts.product;
                    if (pe == null)
                    {
                        this.xtbc.SelectedIndex = 3;
                        _expander.IsExpanded    = true;
                    }

                    else
                    {
                        res = "Products id=[" + lp[0].CustumerId.ToString() + "]";
                    }

                    break;
                }
            }

            return(res);
        }
        /// <summary>
        /// Renders a quote element.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="blockUIElementCollection"></param>
        private void RenderQuote(QuoteBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            if (QuoteForeground != null)
            {
                context = context.Clone();
                context.Foreground = QuoteForeground;
            }

            var stackPanel = new StackPanel();
            RenderBlocks(element.Blocks, stackPanel.Children, context);

            var border = new Border();
            border.Margin = QuoteMargin;
            border.Background = QuoteBackground;
            border.BorderBrush = QuoteBorderBrush ?? context.Foreground;
            border.BorderThickness = QuoteBorderThickness;
            border.Padding = QuotePadding;
            border.Child = stackPanel;

            blockUIElementCollection.Add(border);
        }
        protected override Size MeasureOverride(Size availableSize)
        {
            Panel panel = this.GroupLevelIndicatorPaneHost;

            if (panel == null)
            {
                return(base.MeasureOverride(availableSize));
            }

            DataGridContext dataGridContext = DataGridControl.GetDataGridContext(this);

            if (dataGridContext != null)
            {
                ObservableCollection <GroupDescription> groupDescriptions = DataGridContext.GetGroupDescriptionsHelper(dataGridContext.Items);

                int leafGroupLevel = GroupLevelIndicatorPane.GetGroupLevel(this);

                // If Indented is true (default), we use the total groupDescriptions.Count for this DataGridContext
                int correctedGroupLevel = (this.Indented == true) ? groupDescriptions.Count : leafGroupLevel;

                // Ensure that the GroupLevel retrieved does not exceeds the number of group descriptions for the DataGridContext
                correctedGroupLevel = Math.Min(correctedGroupLevel, groupDescriptions.Count);

                // Then finally, if the GroupLevel is -1, then indent at maximum.
                if (correctedGroupLevel == -1)
                {
                    correctedGroupLevel = groupDescriptions.Count;
                }

                if ((correctedGroupLevel > 0) &&
                    (this.AreGroupsFlattened))
                {
                    correctedGroupLevel = (this.Indented) ? 1 : 0;
                }

                UIElementCollection children = panel.Children;
                int childrenCount            = children.Count;

                // If we need to add/remove GroupLevelIndicators from the panel
                if (correctedGroupLevel != childrenCount)
                {
                    // When grouping change, we take for granted that the group deepness will change,
                    // so we initialize DataContext of the margin only in there.

                    // Clear all the panel's children!
                    children.Clear();

                    // Create 1 group margin content presenter for each group level
                    for (int i = correctedGroupLevel - 1; i >= 0; i--)
                    {
                        GroupLevelIndicator groupMargin = new GroupLevelIndicator();
                        groupMargin.DataContext = dataGridContext.GroupLevelDescriptions[i];
                        children.Insert(0, new GroupLevelIndicator());
                    }

                    childrenCount = correctedGroupLevel;
                    this.SetCurrentIndicatorCount(childrenCount);
                }

                object item = dataGridContext.GetItemFromContainer(this);

                for (int i = 0; i < childrenCount; i++)
                {
                    GroupLevelIndicator groupMargin = children[i] as GroupLevelIndicator;

                    CollectionViewGroup groupForIndicator = GroupLevelIndicatorPane.GetCollectionViewGroupHelper(
                        dataGridContext, groupDescriptions, item, i);

                    GroupConfiguration groupLevelConfig = GroupConfiguration.GetGroupConfiguration(
                        dataGridContext, groupDescriptions, dataGridContext.GroupConfigurationSelector, i, groupForIndicator);

                    if (groupLevelConfig != null)
                    {
                        Binding groupLevelIndicatorStyleBinding = BindingOperations.GetBinding(groupMargin, GroupLevelIndicator.StyleProperty);

                        if ((groupLevelIndicatorStyleBinding == null) || (groupLevelIndicatorStyleBinding.Source != groupLevelConfig))
                        {
                            groupLevelIndicatorStyleBinding        = new Binding("GroupLevelIndicatorStyle");
                            groupLevelIndicatorStyleBinding.Source = groupLevelConfig;
                            // Use a Converter to manage groupLevelConfig.GroupLevelIndicatorStyle == null
                            // so that an implicit syle won't be overriden by a null style.
                            groupLevelIndicatorStyleBinding.Converter          = new GroupLevelIndicatorConverter();
                            groupLevelIndicatorStyleBinding.ConverterParameter = groupMargin;
                            groupMargin.SetBinding(GroupLevelIndicator.StyleProperty, groupLevelIndicatorStyleBinding);
                        }
                    }
                    else
                    {
                        groupMargin.ClearValue(GroupLevelIndicator.StyleProperty);
                    }

                    // If the ShowIndicators property is False or there is already leafGroupLevel GroupLevelIndicators in the panel,
                    // the current newGroupMargin must be hidden.
                    if ((!GroupLevelIndicatorPane.GetShowIndicators(this)) || ((i >= leafGroupLevel) && (leafGroupLevel != -1)))
                    {
                        groupMargin.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        groupMargin.Visibility = Visibility.Visible;
                    }
                }
            }

            return(base.MeasureOverride(availableSize));
        }
예제 #9
0
        /// <summary>
        /// Arranges and sizes the
        /// <see cref="T:WinRTXamlToolkit.Controls.WrapPanel" /> control and its
        /// child elements.
        /// </summary>
        /// <param name="finalSize">
        /// The area within the parent that the
        /// <see cref="T:WinRTXamlToolkit.Controls.WrapPanel" /> should use
        /// arrange itself and its children.
        /// </param>
        /// <returns>
        /// The actual size used by the
        /// <see cref="T:WinRTXamlToolkit.Controls.WrapPanel" />.
        /// </returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            // Variables tracking the size of the current line, and the maximum
            // size available to fill.  Note that the line might represent a row
            // or a column depending on the orientation.
            Orientation  o           = Orientation;
            OrientedSize lineSize    = new OrientedSize(o);
            OrientedSize maximumSize = new OrientedSize(o, finalSize.Width, finalSize.Height);

            // Determine the constraints for individual items
            double itemWidth      = ItemWidth;
            double itemHeight     = ItemHeight;
            bool   hasFixedWidth  = !itemWidth.IsNaN();
            bool   hasFixedHeight = !itemHeight.IsNaN();
            double indirectOffset = 0;
            double?directDelta    = (o == Orientation.Horizontal) ?
                                    (hasFixedWidth ? (double?)itemWidth : null) :
                                    (hasFixedHeight ? (double?)itemHeight : null);

            // Measure each of the Children.  We will process the elements one
            // line at a time, just like during measure, but we will wait until
            // we've completed an entire line of elements before arranging them.
            // The lineStart and lineEnd variables track the size of the
            // currently arranged line.
            UIElementCollection children = Children;
            int count     = children.Count;
            int lineStart = 0;

            for (int lineEnd = 0; lineEnd < count; lineEnd++)
            {
                UIElement element = children[lineEnd];

                // Get the size of the element
                OrientedSize elementSize = new OrientedSize(
                    o,
                    hasFixedWidth ? itemWidth : element.DesiredSize.Width,
                    hasFixedHeight ? itemHeight : element.DesiredSize.Height);

                // If this element falls of the edge of the line
                if (NumericExtensions.IsGreaterThan(lineSize.Direct + elementSize.Direct, maximumSize.Direct))
                {
                    // Then we just completed a line and we should arrange it
                    ArrangeLine(lineStart, lineEnd, directDelta, indirectOffset, lineSize.Indirect);

                    // Move the current element to a new line
                    indirectOffset += lineSize.Indirect;
                    lineSize        = elementSize;

                    // If the current element is larger than the maximum size
                    if (NumericExtensions.IsGreaterThan(elementSize.Direct, maximumSize.Direct))
                    {
                        // Arrange the element as a single line
                        ArrangeLine(lineEnd, ++lineEnd, directDelta, indirectOffset, elementSize.Indirect);

                        // Move to a new line
                        indirectOffset += lineSize.Indirect;
                        lineSize        = new OrientedSize(o);
                    }

                    // Advance the start index to a new line after arranging
                    lineStart = lineEnd;
                }
                else
                {
                    // Otherwise just add the element to the end of the line
                    lineSize.Direct  += elementSize.Direct;
                    lineSize.Indirect = Math.Max(lineSize.Indirect, elementSize.Indirect);
                }
            }

            // Arrange any elements on the last line
            if (lineStart < count)
            {
                ArrangeLine(lineStart, count, directDelta, indirectOffset, lineSize.Indirect);
            }

            return(finalSize);
        }
        private static TreeViewItem GetTreeViewItem(ItemsControl container, object item)
        {
            if (container != null)
            {
                if (container.DataContext == item)
                {
                    return(container as TreeViewItem);
                }

                // Expand the current container
                if (container is TreeViewItem treeViewItem && !treeViewItem.IsExpanded)
                {
                    container.SetValue(TreeViewItem.IsExpandedProperty, true);
                }

                // Try to generate the ItemsPresenter and the ItemsPanel.
                // by calling ApplyTemplate.  Note that in the
                // virtualizing case even if the item is marked
                // expanded we still need to do this step in order to
                // regenerate the visuals because they may have been virtualized away.
                container.ApplyTemplate();
                ItemsPresenter itemsPresenter = (ItemsPresenter)container.Template.FindName("ItemsHost", container);
                if (itemsPresenter != null)
                {
                    itemsPresenter.ApplyTemplate();
                }
                else
                {
                    // The Tree template has not named the ItemsPresenter,
                    // so walk the descendents and find the child.
                    itemsPresenter = container.GetVisualDescendant <ItemsPresenter>();
                    if (itemsPresenter == null)
                    {
                        container.UpdateLayout();
                        itemsPresenter = container.GetVisualDescendant <ItemsPresenter>();
                    }
                }

                Panel itemsHostPanel = (Panel)VisualTreeHelper.GetChild(itemsPresenter, 0);

                // Ensure that the generator for this panel has been created.
                // ReSharper disable UnusedVariable
                UIElementCollection children = itemsHostPanel.Children;
                // ReSharper restore UnusedVariable

                Action <int> bringIndexIntoView = GetBringIndexIntoView(itemsHostPanel);
                for (int i = 0, count = container.Items.Count; i < count; i++)
                {
                    TreeViewItem subContainer;
                    if (bringIndexIntoView != null)
                    {
                        // Bring the item into view so
                        // that the container will be generated.
                        bringIndexIntoView(i);
                        subContainer = (TreeViewItem)container.ItemContainerGenerator.ContainerFromIndex(i);
                    }
                    else
                    {
                        subContainer = (TreeViewItem)container.ItemContainerGenerator.ContainerFromIndex(i);

                        // Bring the item into view to maintain the
                        // same behavior as with a virtualizing panel.
                        subContainer.BringIntoView();
                    }

                    if (subContainer == null)
                    {
                        continue;
                    }

                    // Search the next level for the object.
                    TreeViewItem resultContainer = GetTreeViewItem(subContainer, item);
                    if (resultContainer != null)
                    {
                        return(resultContainer);
                    }

                    // The object is not under this TreeViewItem
                    // so collapse it.
                    subContainer.IsExpanded = false;
                }
            }

            return(null);
        }
예제 #11
0
 public TreeGridCellsPanel()
 {
     this._additionalChildren = new UIElementCollection(this, this);
 }
예제 #12
0
 /// <summary>
 /// Creates a new instance of <see cref="UIElement"/>.
 /// </summary>
 protected UIElement()
 {
     Id = Guid.NewGuid();
     DependencyProperties = new PropertyContainerClass(this);
     VisualChildrenCollection = new UIElementCollection();
 }
        /// <summary>
        /// Renders a header element.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        private void RenderHeader(HeaderBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            var textBlock = CreateOrReuseRichTextBlock(blockUIElementCollection, context);

            var paragraph = new Paragraph();
            var childInlines = paragraph.Inlines;
            switch (element.HeaderLevel)
            {
                case 1:
                    paragraph.Margin = Header1Margin;
                    paragraph.FontSize = Header1FontSize;
                    paragraph.FontWeight = Header1FontWeight;
                    break;
                case 2:
                    paragraph.Margin = Header2Margin;
                    paragraph.FontSize = Header2FontSize;
                    paragraph.FontWeight = Header2FontWeight;
                    break;
                case 3:
                    paragraph.Margin = Header3Margin;
                    paragraph.FontSize = Header3FontSize;
                    paragraph.FontWeight = Header3FontWeight;
                    break;
                case 4:
                    paragraph.Margin = Header4Margin;
                    paragraph.FontSize = Header4FontSize;
                    paragraph.FontWeight = Header4FontWeight;
                    break;
                case 5:
                    paragraph.Margin = Header5Margin;
                    paragraph.FontSize = Header5FontSize;
                    paragraph.FontWeight = Header5FontWeight;
                    break;
                case 6:
                    paragraph.Margin = Header6Margin;
                    paragraph.FontSize = Header6FontSize;
                    paragraph.FontWeight = Header6FontWeight;

                    var underline = new Underline();
                    childInlines = underline.Inlines;
                    paragraph.Inlines.Add(underline);
                    break;
            }

            // Render the children into the para inline.
            context.TrimLeadingWhitespace = true;
            RenderInlineChildren(childInlines, element.Inlines, paragraph, context);

            // Add it to the blocks
            textBlock.Blocks.Add(paragraph);
        }
        /// <summary>
        /// Renders a horizontal rule element.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        private void RenderHorizontalRule(HorizontalRuleBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            var rectangle = new Rectangle();
            rectangle.HorizontalAlignment = HorizontalAlignment.Stretch;
            rectangle.Height = HorizontalRuleThickness;
            rectangle.Fill = HorizontalRuleBrush ?? context.Foreground;
            rectangle.Margin = HorizontalRuleMargin;

            blockUIElementCollection.Add(rectangle);
        }
        /// <summary>
        /// Renders a list of block elements.
        /// </summary>
        /// <param name="blockElements"></param>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        private void RenderBlocks(IEnumerable<MarkdownBlock> blockElements, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            foreach (MarkdownBlock element in blockElements)
            {
                RenderBlock(element, blockUIElementCollection, context);
            }

            // Remove the top margin from the first block element, the bottom margin from the last block element,
            // and collapse adjacent margins.
            FrameworkElement previousFrameworkElement = null;
            for (int i = 0; i < blockUIElementCollection.Count; i++)
            {
                var frameworkElement = blockUIElementCollection[i] as FrameworkElement;
                if (frameworkElement != null)
                {
                    if (i == 0)
                    {
                        // Remove the top margin.
                        frameworkElement.Margin = new Thickness(
                            frameworkElement.Margin.Left,
                            0,
                            frameworkElement.Margin.Right,
                            frameworkElement.Margin.Bottom);
                    }
                    else if (previousFrameworkElement != null)
                    {
                        // Remove the bottom margin.
                        frameworkElement.Margin = new Thickness(
                            frameworkElement.Margin.Left,
                            Math.Max(frameworkElement.Margin.Top, previousFrameworkElement.Margin.Bottom),
                            frameworkElement.Margin.Right,
                            frameworkElement.Margin.Bottom);
                        previousFrameworkElement.Margin = new Thickness(
                            previousFrameworkElement.Margin.Left,
                            previousFrameworkElement.Margin.Top,
                            previousFrameworkElement.Margin.Right,
                            0);

                    }
                }
                previousFrameworkElement = frameworkElement;
            }
        }
        /// <summary>
        /// Renders a code element.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        private void RenderCode(CodeBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            var textBlock = CreateTextBlock(context);
            textBlock.FontFamily = CodeFontFamily ?? FontFamily;
            textBlock.Foreground = CodeForeground ?? context.Foreground;
            textBlock.LineHeight = FontSize * 1.4;
            textBlock.Text = element.Text;

            var border = new Border();
            border.Background = CodeBackground;
            border.BorderBrush = CodeBorderBrush;
            border.BorderThickness = CodeBorderThickness;
            border.Padding = CodePadding;
            border.Margin = CodeMargin;
            border.HorizontalAlignment = HorizontalAlignment.Left;
            border.Child = textBlock;

            // Add it to the blocks
            blockUIElementCollection.Add(border);
        }
 /// <summary>
 /// Called to render a block element.
 /// </summary>
 /// <param name="element"></param>
 /// <param name="blockUIElementCollection"></param>
 /// <param name="context"></param>
 private void RenderBlock(MarkdownBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
 {
     switch (element.Type)
     {
         case MarkdownBlockType.Paragraph:
             RenderParagraph((ParagraphBlock)element, blockUIElementCollection, context);
             break;
         case MarkdownBlockType.Quote:
             RenderQuote((QuoteBlock)element, blockUIElementCollection, context);
             break;
         case MarkdownBlockType.Code:
             RenderCode((CodeBlock)element, blockUIElementCollection, context);
             break;
         case MarkdownBlockType.Header:
             RenderHeader((HeaderBlock)element, blockUIElementCollection, context);
             break;
         case MarkdownBlockType.List:
             RenderListElement((ListBlock)element, blockUIElementCollection, context);
             break;
         case MarkdownBlockType.HorizontalRule:
             RenderHorizontalRule((HorizontalRuleBlock)element, blockUIElementCollection, context);
             break;
         case MarkdownBlockType.Table:
             RenderTable((TableBlock)element, blockUIElementCollection, context);
             break;
     }
 }
        /// <summary>
        /// Creates a new RichTextBlock, if the last element of the provided collection isn't already a RichTextBlock.
        /// </summary>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private RichTextBlock CreateOrReuseRichTextBlock(UIElementCollection blockUIElementCollection, RenderContext context)
        {
            // Reuse the last RichTextBlock, if possible.
            if (blockUIElementCollection != null && blockUIElementCollection.Count > 0 && blockUIElementCollection[blockUIElementCollection.Count - 1] is RichTextBlock)
                return (RichTextBlock)blockUIElementCollection[blockUIElementCollection.Count - 1];

            var result = new RichTextBlock();
            result.CharacterSpacing = CharacterSpacing;
            result.FontFamily = FontFamily;
            result.FontSize = FontSize;
            result.FontStretch = FontStretch;
            result.FontStyle = FontStyle;
            result.FontWeight = FontWeight;
            result.Foreground = context.Foreground;
            result.IsTextSelectionEnabled = IsTextSelectionEnabled;
            result.TextWrapping = TextWrapping;
            if (blockUIElementCollection != null)
                blockUIElementCollection.Add(result);
            return result;
        }
        /// <summary>
        /// Renders a table element.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        private void RenderTable(TableBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            var table = new MarkdownTable(element.ColumnDefinitions.Count, element.Rows.Count, TableBorderThickness, TableBorderBrush);
            table.HorizontalAlignment = HorizontalAlignment.Left;
            table.Margin = TableMargin;

            // Add each row.
            for (int rowIndex = 0; rowIndex < element.Rows.Count; rowIndex++)
            {
                var row = element.Rows[rowIndex];

                // Add each cell.
                for (int cellIndex = 0; cellIndex < Math.Min(element.ColumnDefinitions.Count, row.Cells.Count); cellIndex++)
                {
                    var cell = row.Cells[cellIndex];

                    // Cell content.
                    var cellContent = CreateOrReuseRichTextBlock(null, context);
                    cellContent.Margin = TableCellPadding;
                    Grid.SetRow(cellContent, rowIndex);
                    Grid.SetColumn(cellContent, cellIndex);
                    switch (element.ColumnDefinitions[cellIndex].Alignment)
                    {
                        case ColumnAlignment.Center:
                            cellContent.TextAlignment = TextAlignment.Center;
                            break;
                        case ColumnAlignment.Right:
                            cellContent.TextAlignment = TextAlignment.Right;
                            break;
                    }
                    if (rowIndex == 0)
                        cellContent.FontWeight = FontWeights.Bold;
                    var paragraph = new Paragraph();
                    context.TrimLeadingWhitespace = true;
                    RenderInlineChildren(paragraph.Inlines, cell.Inlines, paragraph, context);
                    cellContent.Blocks.Add(paragraph);
                    table.Children.Add(cellContent);
                }
            }

            blockUIElementCollection.Add(table);
        }
예제 #20
0
 protected Shape() : base("svg", isSvg: true)
 {
     _svgChildren = new UIElementCollection(this);
 }
        /// <summary>
        /// Renders a list element.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        private void RenderListElement(ListBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            // Create a grid with two columns.
            Grid grid = new Grid();
            grid.Margin = ListMargin;

            // The first column for the bullet (or number) and the second for the text.
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(ListGutterWidth) });
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

            for (int rowIndex = 0; rowIndex < element.Items.Count; rowIndex ++)
            {
                var listItem = element.Items[rowIndex];

                // Add a row definition.
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                // Add the bullet or number.
                var bullet = CreateTextBlock(context);
                bullet.Margin = ParagraphMargin;
                switch (element.Style)
                {
                    case ListStyle.Bulleted:
                        bullet.Text = "•";
                        break;
                    case ListStyle.Numbered:
                        bullet.Text = $"{rowIndex + 1}.";
                        break;
                }
                bullet.HorizontalAlignment = HorizontalAlignment.Right;
                bullet.Margin = new Thickness(0, 0, ListBulletSpacing, 0);
                Grid.SetRow(bullet, rowIndex);
                grid.Children.Add(bullet);

                // Add the list item content.
                var content = new StackPanel();
                RenderBlocks(listItem.Blocks, content.Children, context);
                Grid.SetColumn(content, 1);
                Grid.SetRow(content, rowIndex);
                grid.Children.Add(content);
            }

            blockUIElementCollection.Add(grid);
        }
예제 #22
0
 protected ContainerElement()
 {
     Children = new UIElementCollection(this);
 }
예제 #23
0
파일: GameBase.cs 프로젝트: mbg/FSEGame
        /// <summary>
        /// Initialises the game.
        /// </summary>
        protected GameBase()
        {
            GameBase.singleton = this;

            this.uiElements = new UIElementCollection();
            this.fpsCounter = new FPSCounter();

            this.persistentStorage = new PersistentStorage();

            // :: Initialise Lua and register the Engine's functions.
            this.luaState = new Lua();
            this.RegisterClass(this);

            // :: Initialise the graphics device manager and register some events.
            this.graphics = new GraphicsDeviceManager(this);
            this.graphics.PreparingDeviceSettings +=
                new EventHandler<PreparingDeviceSettingsEventArgs>(PrepareGraphicsSettings);

            this.dialogueManager = new DialogueManager();

            this.Content.RootDirectory = "FSEGame";
        }
예제 #24
0
파일: ControlO.cs 프로젝트: Miraxek/X90
 public void RemoveFrom(UIElementCollection collection)
 {
     collection.Remove(circle);
 }
예제 #25
0
        private void LoadPage(int index, bool clearImprs)
        {
            if (index == 0)
            {
                oldMode = Mode;
            }

            UIElementCollection items = RaceBarBackground.Children;
            int j = 0;

            for (int i = index; i < index + 5; i++)
            {
                RaceBarItem       item   = (RaceBarItem)items[j++];
                int               pos    = j + (index * 5);
                LiveStandingsItem stItem = Module.Items.Find(it => it.PositionLive == pos);
                if (stItem == null)
                {
                    item.Show = false;
                    continue;
                }

                if (clearImprs)
                {
                    stItem.PositionImprovedRaceBar = stItem.PositionLostRaceBar = false;
                }

                item.Show = true;

                if (stItem.PositionLive == 1)
                {
                    item.NumberLeader.Visibility = Visibility.Visible;
                }
                else
                {
                    item.NumberLeader.Visibility = Visibility.Hidden;
                }

                item.Position.Text          = stItem.PositionLive.ToString();
                item.ClassColorLeader.Color = stItem.Driver.LicColor; // TODO ClassColor
                item.ClassColorNormal.Color = stItem.Driver.LicColor;

                /*
                 * if (stItem.PositionImprovedRaceBar)
                 * {
                 *  item.PositionImproved();
                 *  stItem.PositionImprovedRaceBar = false;
                 * }
                 *
                 * if (stItem.PositionLostRaceBar)
                 * {
                 *  item.PositionLost();
                 *  stItem.PositionLostRaceBar = false;
                 * }
                 */
                switch (oldMode)
                {
                case RaceBarMode.Gap:
                    item.ThreeLetterCode.Visibility = Visibility.Visible;
                    item.GapText.Visibility         = Visibility.Visible;
                    item.DriverName.Visibility      = Visibility.Hidden;

                    checkPits(item, stItem);

                    item.ThreeLetterCode.Text = stItem.Driver.ThreeLetterCode;
                    if (stItem.PositionLive == 1)
                    {
                        item.GapText.Text = "Leader";
                    }
                    else
                    {
                        if (stItem.GapLaps == 0)
                        {
                            if (Live)
                            {
                                item.GapText.Text = "+" + stItem.GapLiveLeader.ConvertToTimeString();
                            }
                            else
                            {
                                item.GapText.Text = "+" + stItem.GapTime.ConvertToTimeString();
                            }
                        }
                        else
                        {
                            item.GapText.Text = "+" + stItem.GapLaps.ToString() + (stItem.GapLaps == 1 ? " Lap" : " Laps");
                        }
                    }
                    break;

                case RaceBarMode.Interval:
                    item.ThreeLetterCode.Visibility = Visibility.Visible;
                    item.GapText.Visibility         = Visibility.Visible;
                    item.DriverName.Visibility      = Visibility.Hidden;

                    checkPits(item, stItem);

                    item.ThreeLetterCode.Text = stItem.Driver.ThreeLetterCode;
                    if (stItem.PositionLive == 1)
                    {
                        item.GapText.Text = "Interval";
                    }
                    else
                    {
                        float gap = 0;
                        if (Live)
                        {
                            gap = stItem.GapLive;
                        }
                        else
                        {
                            LiveStandingsItem stItem2 = Module.Items.Find(it => it.PositionLive == (j + (index * 5)) - 1);
                            gap = stItem.GapTime - stItem2.GapTime;
                        }

                        item.GapText.Text = "+" + gap.ConvertToTimeString();
                    }
                    break;

                case RaceBarMode.Name:
                    item.ThreeLetterCode.Visibility = Visibility.Hidden;
                    item.GapText.Visibility         = Visibility.Hidden;
                    item.PitText.Visibility         = Visibility.Hidden;
                    item.DriverName.Visibility      = Visibility.Visible;

                    item.DriverName.Text = stItem.Driver.LastUpperName;
                    break;

                default:
                    break;
                }
            }
        }
예제 #26
0
 public TabControl( )
 {
     controls = new UIElementCollection( this );
     AddHandler(MouseDownEvent, new MouseButtonEventHandler(mouseDown));
 }
예제 #27
0
 public Panel()
 {
     _Children = new UIElementCollection(this);
 }
        //等分圆周 显示中间和周围图标
        private void DivideCircleOnShowMenu()
        {
            //获取孩子节点
            UIElementCollection children = this.Children;

            FrameworkElement f;


            //外圆半径
            double outCircleRadius = this.Width / 2 - IconWidthAndHeight / 2;

            //平分度数
            double divideEquallyAngle = 360 / (children.Count - 1);

            for (int i = 0; i < children.Count; i++)
            {
                f = children[i] as FrameworkElement;

                //第一个中间图标
                if (i == 0)
                {
                    if (ShowMenu)
                    {
                        f.SetValue(Canvas.TopProperty, outCircleRadius);
                        f.SetValue(Canvas.LeftProperty, outCircleRadius);
                        if (OperateType == OperateEnum.MouseOperate)
                        {
                            f.MouseDown += F_MouseDown;
                        }
                        else
                        {
                            f.TouchUp += F_TouchUp;
                        }
                    }

                    else
                    {
                        f.SetValue(Canvas.TopProperty, outCircleRadius - f.Width / 2);
                        f.SetValue(Canvas.LeftProperty, outCircleRadius - f.Width / 2);
                        f.Visibility = Visibility.Hidden;
                    }
                }

                else
                {
                    //内角度数  角度转换为弧度
                    double innerAngle = divideEquallyAngle * (i - 1) * Math.PI / 180;

                    //TOP距离
                    double topHeight = outCircleRadius - Math.Cos(innerAngle) * outCircleRadius;

                    //Left距离
                    double leftWidth = Math.Sin(innerAngle) * outCircleRadius;

                    if (innerAngle <= 180)
                    {
                        f.SetValue(Canvas.TopProperty, topHeight);
                        f.SetValue(Canvas.LeftProperty, outCircleRadius + leftWidth);
                    }
                    if (innerAngle > 180)
                    {
                        f.SetValue(Canvas.TopProperty, topHeight);
                        f.SetValue(Canvas.LeftProperty, outCircleRadius - leftWidth);
                    }
                }
            }
        }
        public List <ScrubRule> getScrubRules()
        {
            //List<ScrubRule> sb = new List<ScrubRule>();
            TextBox filterCondition = (TextBox)this.FindName("FilterCondition");
            //sb.filterQuery = filterCondition.Text;
            List <ScrubRule> srList = new List <ScrubRule>();

            WrapPanel wrapPanel = (WrapPanel)this.FindName("WrapPanel");

            foreach (UIElement SPUI in wrapPanel.Children)
            {
                Expander            exp          = (Expander)SPUI;
                StackPanel          lrsp         = (StackPanel)exp.Content;
                UIElementCollection uiElementsSP = lrsp.Children;

                ScrubRule sr = new ScrubRule();

                foreach (UIElement uiElementSP in uiElementsSP)
                {
                    StackPanel          tempSP     = (StackPanel)uiElementSP;
                    UIElementCollection uiElements = tempSP.Children;

                    foreach (UIElement uiElement in uiElements)
                    {
                        if (uiElement.GetType().Name == "Label")
                        {
                            var ruleIdLabel = (Label)uiElement;
                            int ruleId;
                            if (int.TryParse(ruleIdLabel.Content.ToString(), out ruleId))
                            {
                                sr.RuleId = ruleId;
                            }
                            else
                            {
                                sr.RuleId = 0;
                            }
                        }

                        if (uiElement.GetType().Name == "TextBox")
                        {
                            TextBox tb = (TextBox)uiElement;

                            if (tb.Name.StartsWith("Filter"))
                            {
                                sr.FilterCondition = tb.Text.Trim();
                            }
                            else if (tb.Name.StartsWith("ScrubAttribute"))
                            {
                                sr.PropertyName = tb.Text.Trim();
                            }
                            else if (tb.Name.StartsWith("ScrubValue"))
                            {
                                sr.UpdateValue = tb.Text.Trim();
                            }
                            else if (tb.Name.StartsWith("FindValue"))
                            {
                                sr.FindValue = tb.Text.Trim();
                            }
                        }

                        if (uiElement.GetType().Name == "ComboBox")
                        {
                            ComboBox cb = (ComboBox)uiElement;
                            if (cb.Name.StartsWith("ScrubType"))
                            {
                                //sr.Type = (RuleType) Enum.Parse(typeof(RuleType), cb.Text);
                                RuleType rType;

                                if (Enum.TryParse <RuleType>(cb.Text, out rType))
                                {
                                    sr.Type = rType;
                                }
                                else
                                {
                                    sr.Type = null;
                                }
                            }
                        }
                    }
                }

                srList.Add(sr);
            }

            return(srList);
        }
        private Size NonStarPassMeasure(Size availableSize)
        {
            UIElementCollection children  = InternalChildren;
            int        childCount         = children.Count;
            double     desiredWidth       = 0;
            double     desiredHeight      = 0;
            double     columnWidth        = 0;
            double     columnHeight       = 0;
            double     maxStarColumnWidth = 0;
            double     starWeight         = 0;
            List <int> starChildIndices   = new List <int>();

            _starLayoutCombinations.Clear();
            _childIndexToStarLayoutIndexMap.Clear();

            for (int i = 0; i < childCount; i++)
            {
                UIElement child = children[i];
                child.Measure(availableSize);
                Size childDesiredSize = child.DesiredSize;

                if (DoubleUtil.GreaterThan(columnHeight + childDesiredSize.Height, availableSize.Height))
                {
                    // When switching to next column, create a star layout combination
                    // for previous column if needed.
                    CreateStarLayoutCombination(availableSize,
                                                starWeight,
                                                columnWidth,
                                                maxStarColumnWidth,
                                                starChildIndices);

                    starWeight    = 0;
                    desiredHeight = Math.Min(Math.Max(desiredHeight, columnHeight), availableSize.Height);
                    columnHeight  = childDesiredSize.Height;
                    desiredWidth += columnWidth;
                    double currentWeight = 0;
                    if (IsStarChild(child, out currentWeight))
                    {
                        starChildIndices.Add(i);
                        starWeight        += currentWeight;
                        maxStarColumnWidth = 0;
                        columnWidth        = GetStarChildMinWidth(child as FrameworkElement, ref maxStarColumnWidth);
                    }
                    else
                    {
                        columnWidth        = childDesiredSize.Width;
                        maxStarColumnWidth = columnWidth;
                    }
                }
                else
                {
                    columnHeight += childDesiredSize.Height;
                    double currentWeight = 0;
                    if (IsStarChild(child, out currentWeight))
                    {
                        starWeight += currentWeight;
                        starChildIndices.Add(i);
                        columnWidth = Math.Max(columnWidth, GetStarChildMinWidth(child as FrameworkElement, ref maxStarColumnWidth));
                    }
                    else
                    {
                        columnWidth        = Math.Max(columnWidth, childDesiredSize.Width);
                        maxStarColumnWidth = Math.Max(maxStarColumnWidth, columnWidth);
                    }
                }
            }
            desiredWidth += columnWidth;
            desiredHeight = Math.Min(Math.Max(desiredHeight, columnHeight), availableSize.Height);
            CreateStarLayoutCombination(availableSize,
                                        starWeight,
                                        columnWidth,
                                        maxStarColumnWidth,
                                        starChildIndices);
            return(new Size(desiredWidth, desiredHeight));
        }
        /// <summary>
        /// Renders a paragraph element.
        /// </summary>
        /// <param name="element"></param>
        /// <param name="blockUIElementCollection"></param>
        /// <param name="context"></param>
        private void RenderParagraph(ParagraphBlock element, UIElementCollection blockUIElementCollection, RenderContext context)
        {
            var paragraph = new Paragraph();
            paragraph.Margin = ParagraphMargin;
            context.TrimLeadingWhitespace = true;
            RenderInlineChildren(paragraph.Inlines, element.Inlines, paragraph, context);

            var textBlock = CreateOrReuseRichTextBlock(blockUIElementCollection, context);
            textBlock.Blocks.Add(paragraph);
        }
예제 #32
0
        public void ArrangeZones(UIElementCollection zones, int spacing)
        {
            int rows = _model.Rows;
            int cols = _model.Columns;

            int[,] cells = _model.CellChildMap;

            if (cells.Length < rows * cols)
            {
                // Merge was not finished yet, rows and cols values are invalid
                return;
            }

            double left, top;

            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    int i = cells[row, col];
                    if (((row == 0) || (cells[row - 1, col] != i)) &&
                        ((col == 0) || (cells[row, col - 1] != i)))
                    {
                        // this is not a continuation of a span
                        GridZone zone = (GridZone)zones[i];
                        left = _colInfo[col].Start;
                        top  = _rowInfo[row].Start;
                        Canvas.SetLeft(zone, left);
                        Canvas.SetTop(zone, top);
                        zone.LabelID.Content = i + 1;

                        int maxRow = row;
                        while (((maxRow + 1) < rows) && (cells[maxRow + 1, col] == i))
                        {
                            maxRow++;
                        }

                        zone.HorizontalSnapPoints = null;
                        if (maxRow > row)
                        {
                            zone.HorizontalSnapPoints = new double[maxRow - row];
                            int pointsIndex = 0;
                            for (int walk = row; walk < maxRow; walk++)
                            {
                                zone.HorizontalSnapPoints[pointsIndex++] = _rowInfo[walk].End + (spacing / 2) - top;
                            }
                        }

                        int maxCol = col;
                        while (((maxCol + 1) < cols) && (cells[row, maxCol + 1] == i))
                        {
                            maxCol++;
                        }

                        zone.VerticalSnapPoints = null;
                        if (maxCol > col)
                        {
                            zone.VerticalSnapPoints = new double[maxCol - col];
                            int pointsIndex = 0;
                            for (int walk = col; walk < maxCol; walk++)
                            {
                                zone.VerticalSnapPoints[pointsIndex++] = _colInfo[walk].End + (spacing / 2) - left;
                            }
                        }

                        zone.MinWidth  = _colInfo[maxCol].End - left;
                        zone.MinHeight = _rowInfo[maxRow].End - top;
                    }
                }
            }
        }
 public ListBoxItemCollection(ListBox listBox, UIElementCollection items)
 {
     _listBox = listBox;
     _items = items;
 }
예제 #34
0
        public void button_ConfirmIngredients_Click(object sender, RoutedEventArgs e)
        {
            currentRecipe = new Recipe();

            bool   abortCalculation = false, validIngredient = false, servingsSpecified = true, measuredByVolume = false;
            double portion, ingrQtyVal = 0; // portion represents how much the ingredient used is compared to one serving size of that ingredient
            double n_servingsMade = 0;


            if (textBox_NumberServingsMade.Text == "")
            {
                servingsSpecified = false;
            }
            else
            {
                try
                {
                    n_servingsMade = Double.Parse(textBox_NumberServingsMade.Text);

                    if (n_servingsMade <= 0)
                    {
                        abortCalculation = true;
                        MessageBox.Show("A number <= 0 was detected.");
                    }
                }
                catch
                {
                    MessageBox.Show("Alpha input detected for number of servings.");
                    abortCalculation = true;
                }
            }

            double totalCalories = 0, totalFat = 0, totalSatFat = 0, totalTransFat = 0, totalCholesterol = 0,
                   totalSodium = 0, totalCarbs = 0, totalFiber = 0, totalSugar = 0, totalProtein = 0, totalPrice = 0;

            // add nutrition from each ingredient entered
            foreach (Grid g in recipeIngredientList)
            {
                if (abortCalculation == false) // an ingredient containing invalid fields has not been found yet
                {
                    UIElementCollection gridChildren   = g.Children;
                    TextBox             ingrQty        = (TextBox)gridChildren[0];
                    ComboBox            ingrMsr        = (ComboBox)gridChildren[1];
                    ComboBox            ingrIngredient = (ComboBox)gridChildren[3];

                    if (ingrQty.Text == "" && ingrMsr.Text == "" && ingrIngredient.Text == "")
                    {
                        // skip adding this ingredient since it was left blank but do not abort
                    }
                    else if (ingrQty.Text == "" || ingrMsr.Text == "" || ingrIngredient.Text == "")
                    {
                        // not all fields were left blank so user forgot a field, abort the calculation and show message
                        abortCalculation = true;

                        String msg = "An empty field was detected for an ingredient.  Either\n"
                                     + "occupy all fields or leave them all blank.";
                        MessageBox.Show(msg);
                    }
                    else
                    {
                        // all fields were entered for the ingredient, now check if they are valid
                        try
                        {
                            ingrQtyVal = Double.Parse(ingrQty.Text);

                            if (ingrQtyVal <= 0)
                            {
                                abortCalculation = true;
                                MessageBox.Show("A number <= 0 was detected.");
                            }
                        }
                        catch (Exception)
                        {
                            abortCalculation = true;
                            MessageBox.Show("Alpha input detected for number of servings.");
                        }


                        String     ingrMsr_AsString = ingrMsr.Text;
                        Ingredient ingredient       = (Ingredient)ingrIngredient.SelectedItem;

                        if (ingrMsr_AsString == "oz" || ingrMsr_AsString == "mg" || ingrMsr_AsString == "g" || ingrMsr_AsString == "kg")
                        {
                            measuredByVolume = false;
                        }
                        else
                        {
                            measuredByVolume = true;
                        }

                        if (measuredByVolume != ingredient.measuredByVolume)
                        {
                            String msg = "Invalid Measurement Type Conversion\n\n";

                            msg += "Recipe calls for " + ingrQty.Text + " " + ingrMsr.Text + " of " + ingredient.ToString() +
                                   " but " + ingredient.ToString() + " is currently only known to be measured by " + ingredient.ServingMsr + ".\n";

                            msg += "Cannot convert a ";
                            if (measuredByVolume == true)
                            {
                                msg += "volume";
                            }
                            else
                            {
                                msg += "mass";
                            }

                            msg += " measurement to a ";
                            if (ingredient.measuredByVolume == true)
                            {
                                msg += "volume";
                            }
                            else
                            {
                                msg += "mass";
                            }

                            msg += " measurement.";

                            MessageBox.Show(msg);

                            abortCalculation = true;
                        }

                        // All fields have been gathered and tested for validity, calculate if we can
                        if (abortCalculation == false)
                        {
                            validIngredient = true; // atleast one ingredient was valid

                            portion = GetPortionSize(ingrQtyVal, ingrMsr_AsString, ingredient);

                            totalCalories    += ingredient.Calories * portion;
                            totalFat         += ingredient.Fat * portion;
                            totalSatFat      += ingredient.SatFat * portion;
                            totalTransFat    += ingredient.TransFat * portion;
                            totalCholesterol += ingredient.Cholesterol * portion;
                            totalSodium      += ingredient.Sodium * portion;
                            totalCarbs       += ingredient.Carbs * portion;
                            totalFiber       += ingredient.Fiber * portion;
                            totalSugar       += ingredient.Sugar * portion;
                            totalProtein     += ingredient.Protein * portion;

                            double pricePerServing = ingredient.Price / ingredient.ServingPerContainer;
                            totalPrice += pricePerServing * portion;

                            // now add the ingredient to the recipe
                            RecipeIngredient rIngredient = new RecipeIngredient(ingrQtyVal, ingrMsr_AsString, ingredient);
                            currentRecipe.ingredients.Add(rIngredient);
                        }
                    }
                }
            }

            label_ServingCalories.Content    = "-";
            label_ServingFat.Content         = "-";
            label_ServingSatFat.Content      = "-";
            label_ServingTransFat.Content    = "-";
            label_ServingCholesterol.Content = "-";
            label_ServingSodium.Content      = "-";
            label_ServingCarbs.Content       = "-";
            label_ServingFiber.Content       = "-";
            label_ServingSugar.Content       = "-";
            label_ServingProtein.Content     = "-";
            label_ServingPrice.Content       = "-";

            label_RecipeCalories.Content    = "-";
            label_RecipeFat.Content         = "-";
            label_RecipeSatFat.Content      = "-";
            label_RecipeTransFat.Content    = "-";
            label_RecipeCholesterol.Content = "-";
            label_RecipeSodium.Content      = "-";
            label_RecipeCarbs.Content       = "-";
            label_RecipeFiber.Content       = "-";
            label_RecipeSugar.Content       = "-";
            label_RecipeProtein.Content     = "-";
            label_RecipePrice.Content       = "-";

            textBox_RecipeName.Text        = "Add a Recipe Name (Click me)";
            textBox_RecipeIngredients.Text = "Ingredients will be added here";
            textBox_RecipeDirections.Text  = "Add directions here.";
            textBox_RecipeNotes.Text       = "Add notes here.";

            if (validIngredient && abortCalculation == false)
            {
                // update nutrition facts label to hold the values
                label_RecipeCalories.Content    = String.Format("{0:0.#}", totalCalories);
                label_RecipeFat.Content         = String.Format("{0:0.#}", totalFat);
                label_RecipeSatFat.Content      = String.Format("{0:0.#}", totalSatFat);
                label_RecipeTransFat.Content    = String.Format("{0:0.#}", totalTransFat);
                label_RecipeCholesterol.Content = String.Format("{0:0.#}", totalCholesterol);
                label_RecipeSodium.Content      = String.Format("{0:0.#}", totalSodium);
                label_RecipeCarbs.Content       = String.Format("{0:0.#}", totalCarbs);
                label_RecipeFiber.Content       = String.Format("{0:0.#}", totalFiber);
                label_RecipeSugar.Content       = String.Format("{0:0.#}", totalSugar);
                label_RecipeProtein.Content     = String.Format("{0:0.#}", totalProtein);
                label_RecipePrice.Content       = "$" + String.Format("{0:0.00}", totalPrice);

                if (servingsSpecified == true) // user did specify how many servings the recipe made (and it is > 0)
                {
                    label_ServingCalories.Content    = String.Format("{0:0.#}", totalCalories / n_servingsMade);
                    label_ServingFat.Content         = String.Format("{0:0.#}", totalFat / n_servingsMade);
                    label_ServingSatFat.Content      = String.Format("{0:0.#}", totalSatFat / n_servingsMade);
                    label_ServingTransFat.Content    = String.Format("{0:0.#}", totalTransFat / n_servingsMade);
                    label_ServingCholesterol.Content = String.Format("{0:0.#}", totalCholesterol / n_servingsMade);
                    label_ServingSodium.Content      = String.Format("{0:0.#}", totalSodium / n_servingsMade);
                    label_ServingCarbs.Content       = String.Format("{0:0.#}", totalCarbs / n_servingsMade);
                    label_ServingFiber.Content       = String.Format("{0:0.#}", totalFiber / n_servingsMade);
                    label_ServingSugar.Content       = String.Format("{0:0.#}", totalSugar / n_servingsMade);
                    label_ServingProtein.Content     = String.Format("{0:0.#}", totalProtein / n_servingsMade);
                    label_ServingPrice.Content       = "$" + String.Format("{0:0.00}", totalPrice / n_servingsMade);
                }
                else // user did not specify a number of servings so just show them the recipe amount automatically
                {
                    if (displayingNutrition == true)
                    {
                        // execute TogglePerRecipe_MouseDown event
                        if (displayingPerServing == true)
                        {
                            // want to show per recipe
                            displayingPerServing = false;

                            label_TogglePerServing.Opacity = 0.6;
                            label_TogglePerRecipe.Opacity  = 1;

                            stackPanel_NutritionLabelPerServing.Visibility = Visibility.Collapsed;
                            stackPanel_NutritionLabelPerRecipe.Visibility  = Visibility.Visible;
                        }
                    }
                }

                // update recipe panel
                String text = "";
                foreach (RecipeIngredient rIngredient in currentRecipe.ingredients)
                {
                    text += " - " + rIngredient.Quantity.ToString() + " " + rIngredient.MeasureType + " " + rIngredient.Ingredient.ToString() + "\n";
                }
                textBox_RecipeIngredients.Text = text.Substring(0, text.Length - 1); // remove last \n

                if (servingsSpecified)
                {
                    textBox_RecipeNotes.Text = "Makes " + n_servingsMade.ToString() + " servings.";
                    currentRecipe.Notes      = "Makes " + n_servingsMade.ToString() + " servings.";
                }
            }
            else
            {
                currentRecipe = new Recipe();
            }
        }
예제 #35
0
 public TabControl( )
 {
     controls = new UIElementCollection(this);
     AddHandler(MouseDownEvent, new MouseButtonEventHandler(mouseDown));
 }
예제 #36
0
        /// <summary>
        /// Arrange children position after measure children size.
        /// </summary>
        /// <param name="finalSize"></param>
        /// <returns></returns>
        protected override Size ArrangeOverride(Size arrangeSize)
        {
            UIElementCollection internalChildren = this.InternalChildren;
            int count = internalChildren.Count;


            double width          = arrangeSize.Width;
            double height         = arrangeSize.Height;
            double highLevelCount = 0;

            for (int i = 0; i < count; i++)
            {
                UIElement element = InternalChildren[i];
                if (element != null && element.Visibility != Visibility.Collapsed)
                {
                    Size      desiredSize = element.DesiredSize;
                    DockLevel dockLevel   = HierarchicalPanel.GetDockLevel(element);
                    if (dockLevel == DockLevel.Low)
                    {
                        width  -= desiredSize.Width;
                        height -= desiredSize.Height;
                    }
                    else
                    {
                        highLevelCount++;
                    }
                }
            }

            double x    = 0.0;
            double y    = 0.0;
            double num2 = 0.0;
            double num3 = 0.0;

            for (int index = 0; index < count; ++index)
            {
                UIElement element = internalChildren[index];
                if (element != null && element.Visibility != Visibility.Collapsed)
                {
                    Size desiredSize = element.DesiredSize;
                    Rect finalRect   = new Rect(x, y, Math.Max(0.0, arrangeSize.Width - (x + num2)), Math.Max(0.0, arrangeSize.Height - (y + num3)));
                    if (HierarchicalPanel.GetDockLevel(element) == DockLevel.Low)
                    {
                        switch (DockPanel.GetDock(element))
                        {
                        case Dock.Left:
                            x += desiredSize.Width;
                            finalRect.Width = desiredSize.Width;
                            break;

                        case Dock.Top:
                            y += desiredSize.Height;
                            finalRect.Height = desiredSize.Height;
                            break;

                        case Dock.Right:
                            num2           += desiredSize.Width;
                            finalRect.X     = Math.Max(0.0, arrangeSize.Width - num2);
                            finalRect.Width = desiredSize.Width;
                            break;

                        case Dock.Bottom:
                            num3            += desiredSize.Height;
                            finalRect.Y      = Math.Max(0.0, arrangeSize.Height - num3);
                            finalRect.Height = desiredSize.Height;
                            break;
                        }
                    }
                    else
                    {
                        switch (DockPanel.GetDock(element))
                        {
                        case Dock.Left:
                            x += width / highLevelCount;
                            finalRect.Width = width / highLevelCount;
                            break;

                        case Dock.Top:
                            y += height / highLevelCount;
                            finalRect.Height = height / highLevelCount;
                            break;

                        case Dock.Right:
                            num2           += width / highLevelCount;
                            finalRect.X     = Math.Max(0.0, arrangeSize.Width - num2);
                            finalRect.Width = desiredSize.Width;
                            break;

                        case Dock.Bottom:
                            num3            += height / highLevelCount;
                            finalRect.Y      = Math.Max(0.0, arrangeSize.Height - num3);
                            finalRect.Height = desiredSize.Height;
                            break;
                        }
                    }
                    element.Arrange(finalRect);
                }
            }
            return(arrangeSize);
        }
예제 #37
0
 public MessageBlock()
 {
     Children = new UIElementCollection(this, this);
 }
예제 #38
0
        public void setSelected(GroupBox grpBox, string textSelector)
        {
            bool flgrbt = false;
            //    Grid grd = (Grid)grpBox.Content;
            UIElementCollection uiec = panelA.Children;

            foreach (UIElement uelement in uiec)
            {
                if (typeof(RadioButton) == uelement.GetType())
                {
                    RadioButton rbtn = (RadioButton)uelement;
                    rbtn.IsChecked = false;
                    if (rbtn.Content.ToString() == textSelector)
                    {
                        rbtn.IsChecked = true;
                        flgrbt         = true;
                    }
                }
            }
            uiec = panelB.Children;

            foreach (UIElement uelement in uiec)
            {
                if (typeof(RadioButton) == uelement.GetType())
                {
                    RadioButton rbtn = (RadioButton)uelement;
                    rbtn.IsChecked = false;
                    if (rbtn.Content.ToString() == textSelector)
                    {
                        rbtn.IsChecked = true;
                        flgrbt         = true;
                    }
                }
            }
            if ((!flgrbt) && (textSelector.Substring(0, textSelector.Length > 15 ? 15 : 0) == "_TypesPayDynamic"))
            {
                int indx = -1;
                if (int.TryParse(textSelector == null ? "-1" : textSelector.Replace("_TypesPayDynamic", ""), out indx))
                {
                    cb.SelectedItem = ClassBond.getTypesPayDBFromId(indx);
                }
            }

            if ((!flgrbt) && (textSelector.Substring(0, textSelector.Length > 13 ? 13 : 0) == "Products id=["))
            {
                string sd = textSelector.Substring(textSelector.IndexOf("[") + 1, textSelector.IndexOf("]") - textSelector.IndexOf("[") - 1);

                Guid g = Guid.Parse(sd);

                List <Class.ClassProducts.product> lp = Class.ClassProducts.listProducts.FindAll(l => l.CustumerId == g);

                switch (lp.Count)
                {
                case 0: statusMes.Content = ("С таким именем продукт не найден "); this.xtbc.SelectedIndex = 3; _expander.IsExpanded = true; break;

                case 1: statusMes.Content = (""); xDescription.Text = lp[0].Name; break;

                default:
                    Class.ClassProducts.product pe = list.SelectedItem as Class.ClassProducts.product;
                    if (pe == null)
                    {
                        this.xtbc.SelectedIndex = 3;
                        _expander.IsExpanded    = true;
                    }

                    //    else

                    xDescription.Text = lp[0].Name;

                    break;
                }
            }
        }
예제 #39
0
 public Grid( ) {
     children = new UIElementCollection(this);
 }
예제 #40
0
        private void _draw3DPies(
            Canvas pieContainer,
            double quadWidth,
            double quadHeight,
            int iGroup)
        {
            ChartModel model = Model;

            double[,] yValues = model.YValues;
            string[] groupLabels  = model.GroupLabels;
            Color[]  seriesColors = model.SeriesColors;

            var pieSize = Math.Min(quadWidth / 2, quadHeight / 2);

            if (iGroup == -1)
            {
                iGroup = 0;
            }

            int    nPies    = yValues.GetUpperBound(1) + 1;
            double pieTotal = 0;

            for (int i = 0; i < nPies; ++i)
            {
                pieTotal += yValues[iGroup, i];
            }

            string           pathXAML = CurrentLookAndFeel.GetPiePathXAML();
            Path             pathElem;
            double           pieStart  = 0;
            List <UIElement> dataElems = null;
            bool             animate   = (AnimationDuration > 0);

            if (animate)
            {
                dataElems = DataElements;
            }

            double perspectiveHeight = pieSize / 4;

            Path[] pieElems = new Path[nPies],
            ringElems = new Path[nPies],
            edgeElems = new Path[nPies];

            if (perspectiveHeight > _MAX_PERSPECTIVE_HEIGHT)
            {
                perspectiveHeight = _MAX_PERSPECTIVE_HEIGHT;
            }

            string             gradientXAML = CurrentLookAndFeel.GetElementGradientXAML();
            TranslateTransform defaultTransform;

            for (int i = 0; i < nPies; ++i)
            {
                double valueRatio = 1 - (yValues[iGroup, i]) / (pieTotal);

                double arcBeginX, arcBeginY, arcEndX, arcEndY;
                arcBeginX = pieSize * Math.Cos(pieStart * Math.PI * 2);
                arcBeginY = pieSize * Math.Sin(pieStart * Math.PI * 2);

                StringBuilder sb = new StringBuilder();
                sb.Append("M0,0L").Append(arcBeginX).Append(",").Append(arcBeginY);

                arcEndX = pieSize * Math.Cos((pieStart + valueRatio) * Math.PI * 2);
                arcEndY = pieSize * Math.Sin((pieStart + valueRatio) * Math.PI * 2);

                if (valueRatio >= .5)
                {
                    sb.Append(" A").Append(pieSize).Append(",").Append(pieSize).Append(" 1 0 0 ");
                }
                else
                {
                    sb.Append(" A").Append(pieSize).Append(",").Append(pieSize).Append(" 1 1 0 ");
                }

                sb.Append(arcEndX).Append(",").Append(arcEndY);
                sb.Append(" z");

                pathElem = CreatePathFromXAMLAndData(pathXAML, sb);
                if (animate)
                {
                    dataElems.Add(pathElem);

                    defaultTransform   = new TranslateTransform();
                    defaultTransform.X = defaultTransform.Y = -10000;
                    pathElem.SetValue(Canvas.RenderTransformProperty, defaultTransform);

                    _pieAnimAngles.Add(pieStart + valueRatio / 2);
                }

                if (gradientXAML != null)
                {
                    SetGradientOnElement(pathElem, gradientXAML, seriesColors[i], 0xe5);
                }
                else
                {
                    SetFillOnElement(pathElem, seriesColors[i]);
                }

                pathElem.SetValue(Rectangle.StrokeProperty, new SolidColorBrush(seriesColors[i]));

                // centroid of the pie triangle
                Point centroid = new Point((arcBeginX + arcEndX) / 3, (arcBeginY + arcEndY) / 3);
                SetExpandosOnElement(pathElem, iGroup, i, centroid);
                if (DisplayToolTip)
                {
                    pathElem.MouseEnter += new MouseEventHandler(ShowToolTip);
                    pathElem.MouseLeave += new MouseEventHandler(HideToolTip);
                }

                pathElem.MouseLeftButtonUp += new MouseButtonEventHandler(ChartDataClicked);



                sb = new StringBuilder();
                sb.Append("M").Append(arcBeginX).Append(",").Append(arcBeginY);
                if (valueRatio >= .5) // major arc
                {
                    sb.Append(" A").Append(pieSize).Append(",").Append(pieSize).Append(" 1 0 0 ");
                }
                else
                {
                    sb.Append(" A").Append(pieSize).Append(" ").Append(pieSize).Append(" 1 1 0 ");
                }

                sb.Append(arcEndX).Append(",").Append(arcEndY);

                sb.Append(" v").Append(perspectiveHeight);
                sb.Append(" M").Append(arcEndX).Append(",").Append(arcEndY + perspectiveHeight);

                if (valueRatio >= .5) // major arc
                {
                    sb.Append(" A").Append(pieSize).Append(",").Append(pieSize).Append(" 1 0 1 ");
                }
                else
                {
                    sb.Append(" A").Append(pieSize).Append(",").Append(pieSize).Append(" 1 1 1 ");
                }

                sb.Append(arcBeginX).Append(",").Append(arcBeginY + perspectiveHeight);
                sb.Append(" v").Append(-perspectiveHeight);

                Path pathRingElem = CreatePathFromXAMLAndData(pathXAML, sb);

                if (gradientXAML != null)
                {
                    SetGradientOnElement(pathRingElem, gradientXAML, seriesColors[i], 0xe5);
                }
                else
                {
                    SetFillOnElement(pathRingElem, seriesColors[i]);
                }

                pathRingElem.SetValue(Rectangle.StrokeProperty, new SolidColorBrush(seriesColors[i]));

                sb = new StringBuilder();
                sb.Append("M0,0L");
                sb.Append(arcBeginX).Append(",").Append(arcBeginY);
                sb.Append("v").Append(perspectiveHeight);
                sb.Append("L").Append(0).Append(",").Append(perspectiveHeight);
                sb.Append("z");
                sb.Append("M0,0L");
                sb.Append(arcEndX).Append(",").Append(arcEndY);
                sb.Append("v").Append(perspectiveHeight);
                sb.Append("L").Append(0).Append(",").Append(perspectiveHeight);
                sb.Append("z");


                Path pathEdgeElem = CreatePathFromXAMLAndData(pathXAML, sb);

                if (animate)
                {
                    dataElems.Add(pathRingElem);

                    defaultTransform   = new TranslateTransform();
                    defaultTransform.X = defaultTransform.Y = -10000;
                    pathRingElem.SetValue(Canvas.RenderTransformProperty, defaultTransform);
                    dataElems.Add(pathEdgeElem);

                    defaultTransform   = new TranslateTransform();
                    defaultTransform.X = defaultTransform.Y = -10000;
                    pathEdgeElem.SetValue(Canvas.RenderTransformProperty, defaultTransform);
                }

                (pathEdgeElem.Data as PathGeometry).FillRule = FillRule.Nonzero;

                if (gradientXAML != null)
                {
                    SetGradientOnElement(pathEdgeElem, gradientXAML, seriesColors[i], 0xe5);
                }
                else
                {
                    SetFillOnElement(pathEdgeElem, seriesColors[i]);
                }

                pathEdgeElem.SetValue(Rectangle.StrokeProperty, new SolidColorBrush(seriesColors[i]));

                if (DisplayToolTip)
                {
                    pathRingElem.MouseEnter += new MouseEventHandler(ShowToolTip);
                    pathRingElem.MouseLeave += new MouseEventHandler(HideToolTip);
                    pathEdgeElem.MouseEnter += new MouseEventHandler(ShowToolTip);
                    pathEdgeElem.MouseLeave += new MouseEventHandler(HideToolTip);
                }
                SetExpandosOnElement(pathRingElem, iGroup, i, centroid);
                SetExpandosOnElement(pathEdgeElem, iGroup, i, centroid);

                pieStart    += valueRatio;
                pieElems[i]  = pathElem;
                ringElems[i] = pathRingElem;
                edgeElems[i] = pathEdgeElem;
            }

            UIElementCollection children = pieContainer.Children;

            // For the top half, edges have preference over rings
            double totalRatio = 0;

            for (int i = 0; i < nPies; ++i)
            {
                if (totalRatio <= .5)
                {
                    children.Add(ringElems[i]);
                }
                totalRatio += (yValues[iGroup, i]) / (pieTotal);
            }

            totalRatio = 0;
            for (int i = 0; i < nPies; ++i)
            {
                if (totalRatio <= .5)
                {
                    children.Add(edgeElems[i]);
                }
                totalRatio += (yValues[iGroup, i]) / (pieTotal);
            }

            // For the bottom half, rings have preference over edges
            totalRatio = 0;
            for (int i = 0; i < nPies; ++i)
            {
                if (totalRatio > .5)
                {
                    children.Add(edgeElems[i]);
                }
                totalRatio += (yValues[iGroup, i]) / (pieTotal);
            }

            totalRatio = 0;
            for (int i = 0; i < nPies; ++i)
            {
                if (totalRatio > .5)
                {
                    children.Add(ringElems[i]);
                }
                totalRatio += (yValues[iGroup, i]) / (pieTotal);
            }

            for (int i = 0; i < nPies; ++i)
            {
                children.Add(pieElems[i]);
            }
        }
예제 #41
0
        /// <summary>
        ///   Measure the children
        /// </summary>
        /// <param name="availableSize"> Size available </param>
        /// <returns> Size desired </returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            UpdateScrollInfo(availableSize);

            // Figure out range that's visible based on layout algorithm
            int firstVisibleItemIndex, lastVisibleItemIndex;

            GetVisibleRange(out firstVisibleItemIndex, out lastVisibleItemIndex);

            // We need to access InternalChildren before the generator to work around a bug
            UIElementCollection     children  = InternalChildren;
            IItemContainerGenerator generator = ItemContainerGenerator;

            // Get the generator position of the first visible data item
            GeneratorPosition startPos = generator.GeneratorPositionFromIndex(firstVisibleItemIndex);

            // Get index where we'd insert the child for this position. If the item is realized
            // (position.Offset == 0), it's just position.Index, otherwise we have to add one to
            // insert after the corresponding child
            int childIndex = (startPos.Offset == 0) ? startPos.Index : startPos.Index + 1;

            using (generator.StartAt(startPos, GeneratorDirection.Forward, true))
            {
                for (int itemIndex = firstVisibleItemIndex;
                     itemIndex <= lastVisibleItemIndex;
                     ++itemIndex, ++childIndex)
                {
                    bool newlyRealized;

                    // Get or create the child
                    var child = generator.GenerateNext(out newlyRealized) as UIElement;
                    if (newlyRealized)
                    {
                        // Figure out if we need to insert the child at the end or somewhere in the middle
                        if (child != null)
                        {
                            if (childIndex >= children.Count)
                            {
                                AddInternalChild(child);
                            }
                            else
                            {
                                InsertInternalChild(childIndex, child);
                            }
                        }
                        generator.PrepareItemContainer(child);
                    }
                    else
                    {
                        // The child has already been created, let's be sure it's in the right spot
                        Debug.Assert(child == children[childIndex], "Wrong child was generated");
                    }

                    // Measurements will depend on layout algorithm
                    if (child != null)
                    {
                        child.Measure(GetChildSize());
                    }
                }
            }

            // Note: this could be deferred to idle time for efficiency
            CleanUpItems(firstVisibleItemIndex, lastVisibleItemIndex);

            return(availableSize);
        }
예제 #42
0
        private void OnSplit(object o, SplitEventArgs e)
        {
            MergeCancelClick(null, null);

            UIElementCollection previewChildren = Preview.Children;
            GridZone            splitee         = (GridZone)o;

            int             spliteeIndex = previewChildren.IndexOf(splitee);
            GridLayoutModel model        = Model;

            int rows = model.Rows;
            int cols = model.Columns;

            Tuple <int, int> rowCol = _data.RowColByIndex(spliteeIndex);
            int foundRow            = rowCol.Item1;
            int foundCol            = rowCol.Item2;

            int newChildIndex = AddZone();

            double offset = e.Offset;
            double space  = e.Space;

            if (e.Orientation == Orientation.Vertical)
            {
                if (splitee.VerticalSnapPoints != null)
                {
                    offset += Canvas.GetLeft(splitee);
                    int  count = splitee.VerticalSnapPoints.Length;
                    bool foundExistingSplit = false;
                    int  splitCol           = foundCol;

                    for (int i = 0; i <= count; i++)
                    {
                        if (foundExistingSplit)
                        {
                            int walkRow = foundRow;
                            while ((walkRow < rows) && (_data.GetIndex(walkRow, foundCol + i) == spliteeIndex))
                            {
                                _data.SetIndex(walkRow++, foundCol + i, newChildIndex);
                            }
                        }

                        if (_data.ColumnBottom(foundCol + i) == offset)
                        {
                            foundExistingSplit = true;
                            splitCol           = foundCol + i;

                            // use existing division
                        }
                    }

                    if (foundExistingSplit)
                    {
                        _data.ReplaceIndicesToMaintainOrder(Preview.Children.Count);
                        _dragHandles.UpdateForExistingVerticalSplit(model, foundRow, splitCol);
                        OnGridDimensionsChanged();
                        return;
                    }

                    while (_data.ColumnBottom(foundCol) < offset)
                    {
                        foundCol++;
                    }

                    offset -= _data.ColumnTop(foundCol);
                }

                _dragHandles.UpdateAfterVerticalSplit(foundCol);
                _data.SplitColumn(foundCol, spliteeIndex, newChildIndex, space, offset, App.Overlay.WorkArea.Width);
                _dragHandles.AddDragHandle(Orientation.Vertical, foundRow, foundCol, model);
            }
            else
            {
                // Horizontal
                if (splitee.HorizontalSnapPoints != null)
                {
                    offset += Canvas.GetTop(splitee);
                    int  count = splitee.HorizontalSnapPoints.Length;
                    bool foundExistingSplit = false;
                    int  splitRow           = foundRow;

                    for (int i = 0; i <= count; i++)
                    {
                        if (foundExistingSplit)
                        {
                            int walkCol = foundCol;
                            while ((walkCol < cols) && (_data.GetIndex(foundRow + i, walkCol) == spliteeIndex))
                            {
                                _data.SetIndex(foundRow + i, walkCol++, newChildIndex);
                            }
                        }

                        if (_data.RowEnd(foundRow + i) == offset)
                        {
                            foundExistingSplit = true;
                            splitRow           = foundRow + i;

                            // use existing division
                        }
                    }

                    if (foundExistingSplit)
                    {
                        _data.ReplaceIndicesToMaintainOrder(Preview.Children.Count);
                        _dragHandles.UpdateForExistingHorizontalSplit(model, splitRow, foundCol);
                        OnGridDimensionsChanged();
                        return;
                    }

                    while (_data.RowEnd(foundRow) < offset)
                    {
                        foundRow++;
                    }

                    offset -= _data.RowStart(foundRow);
                }

                _dragHandles.UpdateAfterHorizontalSplit(foundRow);
                _data.SplitRow(foundRow, spliteeIndex, newChildIndex, space, offset, App.Overlay.WorkArea.Height);
                _dragHandles.AddDragHandle(Orientation.Horizontal, foundRow, foundCol, model);
            }

            var  workArea   = App.Overlay.WorkArea;
            Size actualSize = new Size(workArea.Width, workArea.Height);

            ArrangeGridRects(actualSize);
        }
예제 #43
0
 private static IEnumerable <RadioButton> GetNavigationButtons(UIElementCollection elements)
 {
     return(elements.OfType <RadioButton>());
 }
예제 #44
0
        private void CalculateChildren(VisibleRange visibleRange)
        {
            // We need to access InternalChildren before the generator to work around a bug
            UIElementCollection     children  = this.InternalChildren;
            IItemContainerGenerator generator = this.ItemContainerGenerator;

            int          columCount   = DataSource.Source.Columns.Length;
            ItemsControl itemsControl = ItemsControl.GetItemsOwner(this);

            int lastRow = visibleRange.firstRow + visibleRange.rowCount;

            for (int r = visibleRange.firstRow; r < lastRow; r++)
            {
                int firstVisibleItemInRow  = r * columCount + visibleRange.firstCol;
                int lastVisibleItemInRow   = firstVisibleItemInRow + visibleRange.colCount - 1;
                GeneratorPosition startPos = generator.GeneratorPositionFromIndex(firstVisibleItemInRow);

                // Get index where we'd insert the child for this position. If the item is realized
                // (position.Offset == 0), it's just position.Index, otherwise we have to add one to
                // insert after the corresponding child
                int childIndex = (startPos.Offset == 0) ? startPos.Index : startPos.Index + 1;

                using (generator.StartAt(startPos, GeneratorDirection.Forward, true))
                {
                    for (int itemIndex = firstVisibleItemInRow; itemIndex <= lastVisibleItemInRow; ++itemIndex, ++childIndex)
                    {
                        if (((ItemViewModel)itemsControl.Items[itemIndex]).Item != null)
                        {
                            bool newlyRealized;

                            // Get or create the child
                            UIElement child = generator.GenerateNext(out newlyRealized) as UIElement;
                            if (newlyRealized)
                            {
                                // Figure out if we need to insert the child at the end or somewhere in the middle
                                if (childIndex >= children.Count)
                                {
                                    base.AddInternalChild(child);
                                }
                                else
                                {
                                    base.InsertInternalChild(childIndex, child);
                                }
                                generator.PrepareItemContainer(child);
                                this.DataSource.HoverManager.RegisterItem(child);
                            }
                            else
                            {
                                // The child has already been created, let's be sure it's in the right spot
                                //Debug.Assert(child == children[childIndex], "Wrong child was generated");
                            }

                            // Measurements will depend on layout algorithm
                            if (child != null)
                            {
                                child.Measure(GetChildSize());
                            }
                        }
                    }
                }
            }

            // Note: this could be deferred to idle time for efficiency
            CleanUpItems(visibleRange, columCount);
        }
예제 #45
0
 public UIElementCollectionSpan(UIElementCollection collection, int start, int length)
 {
     Collection = collection;
     Start      = start;
     Length     = length;
 }
예제 #46
0
 public Panel()
 {
     xchildren = new UIElementCollection(this);
 }
예제 #47
0
        // From MSDN : When overridden in a derived class, positions child
        // elements and determines a size for a FrameworkElement derived
        // class.
        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            int firstInLine = 0;

            Size currentColumnSize = new Size();

            double accumulatedWidth = 0;

            UIElementCollection elements = base.InternalChildren;

            for (int i = 0; i < elements.Count; i++)
            {
                Size desiredSize = elements[i].DesiredSize;

                bool breakBefore = (elements[i] is ContentPresenter) ? GetColumnBreakBefore((elements[i] as ContentPresenter).Content as UIElement) : GetColumnBreakBefore(elements[i]);
                bool breakAfter  = (elements[i] is ContentPresenter) ? GetColumnBreakAfter((elements[i] as ContentPresenter).Content as UIElement) : GetColumnBreakAfter(elements[i]);

                // need to switch to another column
                if (breakBefore || currentColumnSize.Height + desiredSize.Height > arrangeBounds.Height)
                {
                    this.ArrangeColumn(accumulatedWidth, currentColumnSize.Width, firstInLine, i, arrangeBounds);

                    accumulatedWidth += currentColumnSize.Width;
                    currentColumnSize = desiredSize;

                    // the element is higher then the constraint - give it a separate column
                    if (desiredSize.Height > arrangeBounds.Height)
                    {
                        this.ArrangeColumn(accumulatedWidth, desiredSize.Width, i, ++i, arrangeBounds);
                        accumulatedWidth += desiredSize.Width;
                        currentColumnSize = new Size();
                    }

                    firstInLine = i;
                }
                else
                if (breakAfter)
                {
                    currentColumnSize.Height += desiredSize.Height;
                    currentColumnSize.Width   = Math.Max(desiredSize.Width, currentColumnSize.Width);

                    this.ArrangeColumn(accumulatedWidth, currentColumnSize.Width, firstInLine, i + 1, arrangeBounds);

                    accumulatedWidth += currentColumnSize.Width;

                    currentColumnSize = new Size();
                    firstInLine       = i + 1;
                    i++;
                }
                else // continue to accumulate a column
                {
                    currentColumnSize.Height += desiredSize.Height;
                    currentColumnSize.Width   = Math.Max(desiredSize.Width, currentColumnSize.Width);
                }
            }

            if (firstInLine < elements.Count)
            {
                this.ArrangeColumn(accumulatedWidth, currentColumnSize.Width, firstInLine, elements.Count, arrangeBounds);
            }

            return(arrangeBounds);
        }
예제 #48
0
파일: ControlO.cs 프로젝트: Miraxek/X90
 public void AddTo(UIElementCollection collection)
 {
     collection.Add(circle);
 }
예제 #49
0
 /// <summary>
 /// Brings  the control in the control collection to top
 /// </summary>
 /// <param name="collection">UI Collection</param>
 /// <param name="control">Element to be brought to front</param>
 public static void SendToFront(this UIElementCollection collection, UIElement control)
 {
     collection.Remove(control);
     collection.Add(control);
 }
예제 #50
0
파일: Shape.wasm.cs 프로젝트: vmartos/uno
        protected Shape() : base("svg", isSvg: true)
        {
            _svgChildren = new UIElementCollection(this);

            OnStretchUpdatedPartial();
        }
        public void DrawFrame(UIElementCollection children)
        {
            this.frameCount++;

            // Draw all shapes in the scene
            for (int i = 0; i < this.things.Count; i++)
            {
                Thing thing = this.things[i];
                if (thing.Brush == null)
                {
                    thing.Brush = new SolidColorBrush(thing.Color);
                    double factor = 0.4 + (((double)thing.Color.R + thing.Color.G + thing.Color.B) / 1600);
                    thing.Brush2 =
                        new SolidColorBrush(
                            System.Windows.Media.Color.FromRgb(
                                (byte)(255 - ((255 - thing.Color.R) * factor)),
                                (byte)(255 - ((255 - thing.Color.G) * factor)),
                                (byte)(255 - ((255 - thing.Color.B) * factor))));
                    thing.BrushPulse = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
                }

                if (thing.State == ThingState.Bouncing)
                {
                    // Pulsate edges
                    double alpha = Math.Cos((0.15 * (thing.FlashCount++) * thing.Hotness) * 0.5) + 0.5;

                    children.Add(
                        this.MakeSimpleShape(
                            this.polyDefs[thing.Shape].Sides,
                            this.polyDefs[thing.Shape].Skip,
                            thing.Size,
                            thing.Theta,
                            thing.Center,
                            thing.Brush,
                            thing.BrushPulse,
                            thing.Size * 0.1,
                            alpha));
                    this.things[i] = thing;
                }
                else
                {
                    if (thing.State == ThingState.Dissolving)
                    {
                        thing.Brush.Opacity = 1.0 - (thing.Dissolve * thing.Dissolve);
                    }

                    children.Add(
                        this.MakeSimpleShape(
                            this.polyDefs[thing.Shape].Sides,
                            this.polyDefs[thing.Shape].Skip,
                            thing.Size,
                            thing.Theta,
                            thing.Center,
                            thing.Brush,
                            (thing.State == ThingState.Dissolving) ? null : thing.Brush2,
                            1,
                            1));
                }
            }

            // Show scores
            if (this.scores.Count != 0)
            {
                int i = 0;
                foreach (var score in this.scores)
                {
                    Label label = MakeSimpleLabel(
                        score.Value.ToString(CultureInfo.InvariantCulture),
                        new Rect(
                            (0.02 + (i * 0.6)) * this.sceneRect.Width,
                            0.01 * this.sceneRect.Height,
                            0.4 * this.sceneRect.Width,
                            0.3 * this.sceneRect.Height),
                        new SolidColorBrush(System.Windows.Media.Color.FromArgb(200, 255, 255, 255)));
                    label.FontSize = Math.Max(1, Math.Min(this.sceneRect.Width / 12, this.sceneRect.Height / 12));
                    children.Add(label);
                    i++;
                }
            }

            // Show game timer
            if (this.gameMode != GameMode.Off)
            {
                TimeSpan span = DateTime.Now.Subtract(this.gameStartTime);
                string   text = span.Minutes.ToString(CultureInfo.InvariantCulture) + ":" + span.Seconds.ToString("00");

                Label timeText = MakeSimpleLabel(
                    text,
                    new Rect(
                        0.1 * this.sceneRect.Width, 0.25 * this.sceneRect.Height, 0.89 * this.sceneRect.Width, 0.72 * this.sceneRect.Height),
                    new SolidColorBrush(System.Windows.Media.Color.FromArgb(160, 255, 255, 255)));
                timeText.FontSize = Math.Max(1, this.sceneRect.Height / 16);
                timeText.HorizontalContentAlignment = HorizontalAlignment.Right;
                timeText.VerticalContentAlignment   = VerticalAlignment.Bottom;
                children.Add(timeText);
            }
        }
예제 #52
0
파일: Panel.cs 프로젝트: RUSshy/ultraviolet
 /// <summary>
 /// Initializes a new instance of the <see cref="Panel"/> class.
 /// </summary>
 /// <param name="uv">The Ultraviolet context.</param>
 /// <param name="name">The element's identifying name within its namescope.</param>
 public Panel(UltravioletContext uv, String name)
     : base(uv, name)
 {
     this.children = new UIElementCollection(this, this);
 }
예제 #53
0
        /// <summary>
        /// Insert the visual for the child in the same order as is is defined in the
        /// VirtualChildren collection so the visuals draw on top of each other in the expected order.
        /// The trick is that GetNodesIntersecting returns the nodes in pretty much random order depending
        /// on how the QuadTree decides to break up the canvas.
        ///
        /// The thing we should avoid is a linear search through the potentially large collection of
        /// IVirtualChildren to compute its visible index which is why we have the _visualPositions map.
        /// We should also avoid a N*M algorithm where N is the number of nodes returned from GetNodesIntersecting
        /// and M is the number of children already visible.  For example, Page down in a zoomed out situation
        /// gives potentially high N and and M which would basically be an O(n2) algorithm.
        ///
        /// So the solution is to use the _visualPositions map to get the expected visual position index
        /// of a given IVirtualChild, then do a binary search through existing visible children to find the
        /// insertion point of the new child.  So this is O(Log M).
        /// </summary>
        /// <param name="child">The IVirtualChild to add visual for</param>
        public void EnsureVisual(IVirtualChild child)
        {
            if (child.Visual != null)
            {
                return;
            }

            FrameworkElement e = child.CreateVisual(this);

            e.SetValue(VirtualChildProperty, child);
            Rect bounds = child.Bounds;

            Canvas.SetLeft(e, bounds.Left);
            Canvas.SetTop(e, bounds.Top);

            // Get the correct absolute position of this child.
            int position = _visualPositions[child];

            // Now do a binary search for the correct insertion position based
            // on the visual positions of the existing visible children.
            UIElementCollection c = Children;
            int min = 0;
            int max = c.Count - 1;

            while (max > min + 1)
            {
                int           i = (min + max) / 2;
                UIElement     v = Children[i];
                IVirtualChild n = v.GetValue(VirtualChildProperty) as IVirtualChild;
                if (n != null)
                {
                    int index = _visualPositions[n];
                    if (index > position)
                    {
                        // search from min to i.
                        max = i;
                    }
                    else
                    {
                        // search from i to max.
                        min = i;
                    }
                }
                else
                {
                    // Any nodes without IVirtualChild should be behind the
                    // IVirtualChildren by definition (like the Backdrop).
                    min = i;
                }
            }

            // If 'max' is the last child in the collection, then we need to see
            // if we have a new last child.
            if (c.Count > 0 && max == c.Count - 1)
            {
                UIElement     v        = c[max];
                IVirtualChild maxchild = v.GetValue(VirtualChildProperty) as IVirtualChild;
                int           maxpos   = position;
                if (maxchild == null || position > _visualPositions[maxchild])
                {
                    // Then we have a new last child!
                    max++;
                }
            }
            if (max < 0)
            {
                c.Add(e);
            }
            else
            {
                c.Insert(max, e);
            }
        }