如果在应用程序资源中进行设置,为什么网格背景色会覆盖整个窗口?

时间:2018-11-29 20:44:08

标签: c# .net wpf xaml background

我想知道为什么即使在XAML主窗口文件中未指定网格面板,在应用程序资源中设置网格的背景颜色也会导致整个窗口被网格背景覆盖。

MainWindow.xaml:

<Window x:Class="TicTacToe.DesktopApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Tic-tac-toe"
        Height="420"
        Width="420"
        ResizeMode="NoResize"
        WindowStyle="SingleBorderWindow">

    <DockPanel>
        <Button Content="Button"></Button>
    </DockPanel>

</Window>

App.xaml:

<Application x:Class="TicTacToe.DesktopApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <Style TargetType="Button">
            <Setter Property="Margin" Value="10" />
        </Style>

        <Style TargetType="Grid">
            <Setter Property="Background" Value="Red" />

            <!--Uncomment the line below to see that button seems to be hidden under the grid.-->
            <!--<Setter Property="Opacity" Value="0.5" />-->
        </Style>

    </Application.Resources>
</Application>

MainWindow.xaml.csApp.xaml.cs仅包含自动生成的代码。没什么特别的。

Visual Studio预览按预期显示窗口:

enter image description here

相反,我得到了:

enter image description here

问题

为什么会这样?是否存在某个隐藏且始终存在的网格,该网格覆盖了整个窗口并被我的样式规则所包含?如果是这样,为什么这样做以及为什么以可察觉的一秒钟的延迟应用它呢?

1 个答案:

答案 0 :(得分:1)

这是可视树设计工具用来在调试时在可视树中选择元素的网格。您可以使用事件设置器,单击网格或通过在非调试模式下运行应用来验证这一点。

<Style TargetType="Grid">
    <Setter Property="Background" Value="Red" />
    <EventSetter Event="PreviewMouseDown" Handler="Grid_PreviewMouseDown"/>
    <!--Uncomment the line below to see that button seems to be hidden under the grid.-->
    <!--<Setter Property="Opacity" Value="0.5" />-->
</Style>

public partial class App : Application
{
    private void Grid_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        MessageBox.Show(VisualTreeHelper.GetParent(sender as Grid).ToString());
    }
}