I am working on UWP app which has few views and a banner ad view. I want the banner ad view to be on the top always, it should not hide behind any other elements.
My setup: I have a stack panel in which there are other elements and the banner is added programmatically as shown in the below snippets.
<Grid>
<StackPanel x:Name="stckPnl" Orientation="Vertical" Margin="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top">
<TextBox x:Name="plcTextbox" Header="PLACEMENT:" Text="123456" TextAlignment="Center"
Margin="0,40,0,0" Height="60" Width="240" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Button x:Name="loadBannerBtn" Content="Load Banner" Click="LoadBanner"
Margin="0,40,0,0" Height="40" Width="240" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<ProgressRing x:Name="LoadingIndicator"
Margin="0,40,0,0" Height="40" Width="240" Visibility="Collapsed" />
</StackPanel>
<Rectangle Width="400" Height="400" Fill="Chocolate" Opacity="0.5" Canvas.ZIndex="40" Margin="20"/>
</Grid>
And I am adding banner as below
_banner = new Banner(plcTextbox.Text.Trim(), AdSize.Banner320x50);
_banner.Margin = new Thickness(0, 40, 0, 0);
_banner.LoadAd();
Canvas.SetZIndex(_banner, 30000);
stckPnl.Children.Add(_banner);
What I have tried so far
I have tried setting z-index on the canvas like Canvas.SetZIndex(_banner, 30000);
but it doesn't work. Even after adding the z-index, the semi-transparent rectangle is shown on the top and the banner gets hidden behind it. When I add z-index on the stack panel > z-index of the semi-transparent rectangle then only the banner is shown on the top.
What should I do to have the banner always on the top irrespective of the parent or siblings of the parent?
z-index works only works for elements within panel elements - thus, even if you set 30000, it would only work for StackPanel
in which it is added. And since the Rectangle
is added after StackPanel
it would continue to be on the top.
The solution for you would be to add Rectangle
before StackPanel
or take Banner
object out of StackPanel