Search code examples
wpfxamlwindowstyles

Why is my XAML Window partially black at the bottom right corner?


I have the following Window:

<Window x:Class="WpfApplication1.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="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen" ShowInTaskbar="True"
    Style="{StaticResource BorderlessWindow}" SizeToContent="WidthAndHeight">

    <Grid>

    </Grid>
</Window>

And in my App.xaml I have the following BorderlessWindow Style:

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:shell="http://schemas.microsoft.com/winfx/2006/xaml/presentation/shell"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style x:Key="BorderlessWindow" TargetType="{x:Type Window}">
            <Setter Property="MinWidth" Value="325" />
            <Setter Property="MinHeight" Value="240" />
            <Setter Property="shell:WindowChrome.WindowChrome">
                <Setter.Value>
                    <shell:WindowChrome CaptionHeight="32"
                                        GlassFrameThickness="0"
                                        ResizeBorderThickness="12" />
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>
</Application>

To get the application running, you need a reference to Microsoft.Windows.Shell. And to be complete: we are using .NET Framework 4.0 and VS 2015.

I have set the SizeToContent="WidthAndHeight" to get a smaller window, but when I do that I get a black "shade" to the right and bottom. With snoop I see that the MainWindow is set to the MinHeight and MinWidth, but the Border inside it isn't.

Why isn't the content resized as well? When the Window is updated by resizing the Window with the mouse the Window looks like expected.


Solution

  • You can add a handler for ContentRendered and force it to redraw once the content is rendered. You can hook it up in xaml or the code behind, here it is in code behind.

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            ContentRendered += OnContentRendered;
        }
    
        private void OnContentRendered(object sender, EventArgs eventArgs)
        {
            InvalidateVisual();
        }
    }