我需要使控件出現在所有其他控件之上,因此它將部分覆蓋它們。如何使覆蓋控制高於所有其他控件?
124
A
回答
120
如果您使用在佈局一個帆布或網格,給控制要在上面提出了更高的zIndex的
從MSDN:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="ZIndex Sample">
<Canvas>
<Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" Fill="blue"/>
<Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="150" Canvas.Left="150" Fill="yellow"/>
<Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" Fill="green"/>
<!-- Reverse the order to illustrate z-index property -->
<Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="300" Canvas.Left="200" Fill="green"/>
<Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="350" Canvas.Left="150" Fill="yellow"/>
<Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="400" Canvas.Left="100" Fill="blue"/>
</Canvas>
</Page>
如果不指定Z-索引時,面板的孩子按照他們指定的順序呈現(即最後一個在頂部)。
如果你想要做更復雜的事情,你可以看看如何在Silverlight中實現ChildWindow。它覆蓋半透明背景並彈出整個RootVisual。
35
網格的同一單元格中的控件將被反向渲染。因此,將一個控件放在另一個控件上的簡單方法是將它放在同一個單元格中。
下面是一個有用的例子,它彈出一個面板,在執行長時間運行的任務時(即,BusyMessage
綁定的屬性不爲空),在視圖中(即用戶控件)禁用所有內容, :
<Grid>
<local:MyUserControl DataContext="{Binding}"/>
<Grid>
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="Visibility"
Value="Visible" />
<Style.Triggers>
<DataTrigger Binding="{Binding BusyMessage}"
Value="{x:Null}">
<Setter Property="Visibility"
Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Border HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="DarkGray"
Opacity=".7" />
<Border HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="White"
Padding="20"
BorderBrush="Orange"
BorderThickness="4">
<TextBlock Text="{Binding BusyMessage}" />
</Border>
</Grid>
</Grid>
8
這是WPF中Adorners的常見功能。裝飾者通常出現在所有其他控件之上,但其他提到z順序的答案可能更適合您的情況。
49
Robert Rossney有很好的解決方案。這是我過去使用的另一種解決方案,將「疊加」與其他內容分開。該解決方案利用所附屬性Panel.ZIndex
將「覆蓋」放在其他任何位置上。您可以在代碼中設置「疊加層」的可見性,也可以使用DataTrigger
。
<Grid x:Name="LayoutRoot">
<Grid x:Name="Overlay" Panel.ZIndex="1000" Visibility="Collapsed">
<Grid.Background>
<SolidColorBrush Color="Black" Opacity=".5"/>
</Grid.Background>
<!-- Add controls as needed -->
</Grid>
<!-- Use whatever layout you need -->
<ContentControl x:Name="MainContent" />
</Grid>
3
<Canvas Panel.ZIndex="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="570">
<!-- YOUR XAML CODE -->
</Canvas>
14
將要帶給前在您的XAML代碼末端的控制。即
<Grid>
<TabControl ...>
</TabControl>
<Button Content="ALways on top of TabControl Button"/>
</Grid>
作品!但我如何將Overlay Grid移動到正確位置? – 2012-04-01 11:53:25
這個覆蓋圖將覆蓋整個窗口,而不僅僅是一個特定的區域。 – 2012-04-02 03:02:21
有史以來最好的解決方案!謝謝! – 2017-10-27 05:44:11