KMC
KMC

Reputation: 20046

DropShadowEffect to a specific element in XAML

I have a Border that consist of other UI Controls like Canvas, Buttons, ComboBox etc. I only want a DropShadowEffect on the Border, but all children Controls end up inheriting the DropShadowEffect.

For example, the following code produce DropShadowEffect on the TextBox, Button, ComboBox. How to I apply DropShadowEffect ONLY to the border?

<Border>
   <Border.Effect>
      <DropShadowEffect ...>
   </Border.Effect>
   <Canvas>
      <TextBox>...</TextBox>
      <Button>...</Button>
      <ComboBox>...<ComboBox>
   </Canvas>
</Border>

Upvotes: 2

Views: 10371

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81313

When a DropShadowEffect is applied to a layout container, such as DockPanel or Canvas, the effect is applied to the visual tree of the element or visual, including all of its child elements.

But following article shows a workaround to achieve this goal here.

Let’s say you have the Border with effect. Just have another border with same position but without the effect, that would resolve the problem -

<Border Margin="10">
   <Border.Effect>
      <DropShadowEffect ...>
   </Border.Effect>
</Border>
<Border Margin="10">
   <Canvas>
      <TextBox>...</TextBox>
      <Button>...</Button>
      <ComboBox>...<ComboBox>
   </Canvas>
</Border>

Upvotes: 3

D J
D J

Reputation: 7028

Bit tricky, I did it like this.

 <ControlTemplate x:Key="ShadowBorderShadowTemplate">
        <!-- Start shadow effect to fragment -->
        <Grid x:Name="Transform">
            <Border BorderThickness="1"
                BorderBrush="Gray"
                Background="{x:Null}"
                Margin="1">
                <Border.Effect>
                    <DropShadowEffect BlurRadius="6"
              Direction="270"
              ShadowDepth="2" />
                </Border.Effect>
            </Border>

            <Border BorderThickness="0"
                    Margin="1,2,1,1"
                    BorderBrush="{x:Null}"
                    Background="White" />
        </Grid>
        <!-- End shadow effect to fragment -->
    </ControlTemplate>

    <ControlTemplate x:Key="ContentControlTemplateWithShadow" 
               TargetType="{x:Type ContentControl}">
        <Grid>
            <!-- Shadow around the left nav -->
            <ContentControl Template="{DynamicResource ShadowBorderShadowTemplate}" />
            <ContentPresenter />
        </Grid>
    </ControlTemplate>

and use the resources like

 <ContentControl Template="{StaticResource ContentControlTemplateWithShadow}">
        <Border>
            <Canvas>
                <TextBox Text="ABCD" Canvas.Left="115" Canvas.Top="134" />
                <Button Canvas.Left="115" Canvas.Top="91">Test</Button>
                <ComboBox Canvas.Left="115" Canvas.Top="54" />
            </Canvas>
        </Border>
    </ContentControl>

Hope it helps..

Upvotes: 2

Related Questions