DropShadowEffect到XAML中的特定元素

时间:2012-11-14 06:25:37

标签: c# wpf xaml effect

我有一个边框,包含其他UI控件,如Canvas,Buttons,ComboBox等。我只想在边框上使用 DropShadowEffect ,但所有子控件都会结束继承 DropShadowEffect

例如,以下代码在TextBox,Button,ComboBox上生成 DropShadowEffect 。 如何将 DropShadowEffect 仅应用于边框?

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

2 个答案:

答案 0 :(得分:2)

有点棘手,我是这样做的。

 <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>

并使用

等资源
 <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>

希望有所帮助......

答案 1 :(得分:2)

DropShadowEffect应用于layout container时,例如DockPanel或Canvas,效果将应用于元素或视觉的可视树,包括其所有子元素。

但下面的文章显示了实现此目标的解决方法here

假设你有边框效果。只需another border with same position but without the effect即可解决问题 -

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