首页 > 解决方案 > 如果在应用程序资源中设置,为什么网格背景颜色会覆盖整个窗口?

问题描述

我想知道为什么在应用程序资源中设置网格的背景颜色会导致整个窗口被网格背景覆盖,即使我没有在 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>

应用程序.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.cs并且App.xaml.cs只包含自动生成的代码。没什么特别的。

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

在此处输入图像描述

而不是它,我得到:

在此处输入图像描述

问题

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

标签: c#.netwpfxamlbackground

解决方案


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

<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());
    }
}

推荐阅读