Bring element forward (Z Index) in Silverlight/WPF

前端 未结 7 1660
有刺的猬
有刺的猬 2020-12-04 19:42

All the documentation and examples I\'m finding online for setting Z-Index to bring an element forward in Silverlight are using a Canvas element as a container.

My i

7条回答
  •  情歌与酒
    2020-12-04 20:12

    I've had to deal with this.

    Say you have an ItemsControl with an ItemTemplate set to an instance of a custom control. Within that control you do Canvas.SetZIndex(this, 99). It won't work, because "this" is not the immediate child of the ItemsControl's ItemsPanel. The ItemsControl creates a ContentPresenter for each item, drops that into the ItemsPanel, and renders the ItemTemplate within the ContentPresenter.

    So, if you want to change the ZIndex within your control, you have to find its ContentPresenter, and change the ZIndex on that. One way is...

            public static T FindVisualParent( this DependencyObject obj )
            where T : DependencyObject
        {
            DependencyObject parent = VisualTreeHelper.GetParent( obj );
            while ( parent != null )
            {
                T typed = parent as T;
                if ( typed != null )
                {
                    return typed;
                }
                parent = VisualTreeHelper.GetParent( parent );
            }
            return null;
        }
                    ContentPresenter foo = this.FindVisualParent();
                Canvas.SetZIndex( foo, 99 );
    

提交回复
热议问题