WPF 视图不隐藏主要 window 内容

WPF View not hiding main window contents

我的主 window 有一个网格(2 行)。第 0 行绑定到几个视图(仅显示相关 xaml 代码):

   <Grid>
    <Grid.RowDefinitions>
          //definition of 2 rows
    </Grid.RowDefinitions>

    <ContentControl Grid.Row="0" Content="{Binding SelectedViewModel}"/>
    
    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Margin="40,51,28,0" Width="449">
          //definition of 2 buttons
    </StackPanel>
</Grid>

而第 1 行包含 2 个按钮(我们称它们为 A 和 B)。当我点击按钮 A 时,视图 A 显示在第 0 行,当我点击按钮 B 时,视图 B 也是如此。每个视图只是一个页面,颜色不同,所以我可以确定视图确实显示了。很简单。

现在我注意到如果我在第 0 行插入一个标签:

   <Grid>
    <Grid.RowDefinitions>
          //definition of 2 rows
    </Grid.RowDefinitions>

    <ContentControl Grid.Row="0" Content="{Binding SelectedViewModel}"/>
    
    <StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Margin="40,51,28,0" Width="449">
        <Label Name="MyLabel" Content="Label" HorizontalAlignment="Left" Margin="188,172,0,0" VerticalAlignment="Top" Height="56" Width="135" FontSize="22"/>
    </StackPanel>

    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Margin="40,51,28,0" Width="449">
          //definition of 2 buttons
    </StackPanel>
</Grid>

视图未覆盖标签,标签仍然可见。如果我查看视图的属性,它的颜色是蓝色,不透明度设置为 100%,所以它应该覆盖主 window 网格上显示的所有内容,不是吗?我做错了什么?

谢谢

詹妮

您可以通过更改声明的顺序将包含 LabelStackPanel 放在 ContentControl 之上:

<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Center" Width="449">
        <Label Name="MyLabel" Content="Label" HorizontalAlignment="Left" VerticalAlignment="Top" Height="56" Width="135" FontSize="22"/>
    </StackPanel>
    
    <ContentControl Grid.Row="0">
        <StackPanel Background="Red" Opacity="1"/>
    </ContentControl>

或者通过为 Panel.ZIndex:

设置一个 > 0 的值
<ContentControl Grid.Row="0" Panel.ZIndex="1">
        <StackPanel Background="Red" Opacity="1"/>
    </ContentControl>

Panel.ZIndex MS Docs

请注意,它位于第 0 行,因此它不会覆盖第 1 行的内容,除非您设置 Grid.RowSpan="2"