Archive

Posts Tagged ‘LINQ’

HowTo: find max ZIndex from a collection of UIElements with LINQ

Based on a relevant answer at

http://stackoverflow.com/questions/1101841/linq-how-to-perform-max-on-a-property-of-all-objects-in-a-collection-and-ret

and some digging into LINQ’s Aggregate method documentation is what I’ve just added to my enhanced version of SilverFlow library’s FloatingWindowHost (copying from FloatingWindowHost.cs at http://clipflair.codeplex.com source code)

        /// <summary>
        /// Sets the specified UIElement topmost.
        /// </summary>
        /// <param name="element">UIElement to set topmost.</param>
        /// <exception cref="ArgumentNullException">UIElement is null</exception>
        private void SetTopmost(UIElement element)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            Canvas.SetZIndex(element, MaxZIndex + 1);
        }

        public int MaxZIndex
        {
          get {
            return FloatingWindows.Aggregate(-1, (maxZIndex, window) => {
              int w = Canvas.GetZIndex(window);
              return (w > maxZIndex) ? w : maxZIndex; 
            });  //Math.Max would be cleaner, but slower to call
          }
        }

Worth noting regarding the code above is that Canvas.ZIndex is an attached property available for UIElements in various containers, not just used when being hosted in a Canvas (see http://stackoverflow.com/questions/569751/controlling-rendering-order-zorder-in-silverlight-without-using-the-canvas-con)

Guess one could even make a SetTopmost and SetBottomMost static extension method for UIElement easily by adapting this code.

%d bloggers like this: