简体   繁体   中英

How to add a dropshadow to a borderless window in WPF

I have a window that is borderless and maximized. I want to add a shadow to this borderless window. I used several methods like adding a Border to the window. It indeed adds a shadow, but when the window is maximized, it just makes the window small and adds the shadow to it.

What I want to have is:

  • When the window is maximized, the shadow is invisible
  • When it is minimized, the shadow is visible

This is a code that I used:

<Border Margin="10">
    <Border.Effect>
        <DropShadowEffect Color="Black"
                          Direction="270"
                          BlurRadius="10"
                          ShadowDepth="3" />
    </Border.Effect>
    <Grid Background="White" />
</Border>

The window does not get smaller, when you maximize it. The Window contains the Border as well as the drop-shadow, so what you perceive as smaller is just the Margin of the border inside the window.

You can create a Style with a trigger that checks for the Maximized state of the parent Window .

<Style x:Key="BorderWindowStyle" TargetType="{x:Type Border}">
   <Setter Property="Margin" Value="10"/>
   <Setter Property="Effect">
      <Setter.Value>
         <DropShadowEffect Color="Black"
                           Direction="270"
                           BlurRadius="10"
                           ShadowDepth="3" />
      </Setter.Value>
   </Setter>
   <Style.Triggers>
      <DataTrigger Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Value="Maximized">
         <Setter Property="Margin" Value="0"/>
         <Setter Property="Effect" Value="{x:Null}"/>
      </DataTrigger>
   </Style.Triggers>
</Style>

Remove the properties that are already set in the style from your Border and reference the style.

<Border Style="{StaticResource BorderWindowStyle}">
   <Grid Background="White" />
</Border>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM