Posts Tagged ‘Max’

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

Based on a relevant answer at

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 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

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

%d bloggers like this: