Prolog
Prolog

Reputation: 3374

Why grid background color covers the whole window if set in application resources?

I'm wondering why setting background color of a grid in application resources results in whole window covered by grid background, even if I don't have grid panel specified in XAML main window file.

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.cs and App.xaml.cs contain only auto generated code. Nothing special.

Visual Studio preview shows window as expected:

enter image description here

Instead of it I'm getting:

enter image description here

Questions

Why it behaves like that? Is there somewhere hidden and always present grid that overlays whole window and gets included by my styling rules? And if so, why it does and why it is applied with the observable delay of a fragment of a second?

Upvotes: 0

Views: 67

Answers (1)

Neil B
Neil B

Reputation: 2224

That is a grid used by the Visual tree design tools to select elements in the visual tree when debugging. You can verify this using an event setter,and clicking the grid, or by running the app, not in debug mode.

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

Upvotes: 1

Related Questions