WPF: Add a dropshadow effect to an element from code-behind

怎甘沉沦 提交于 2019-12-21 03:42:34

问题


I thought this would be something simple but so far i found nothing. How do you do it?


回答1:


just try this

// Get a reference to the Button.
Button myButton = new Button();

// Initialize a new DropShadowBitmapEffect that will be applied
// to the Button.
DropShadowBitmapEffect myDropShadowEffect  = new DropShadowBitmapEffect();
// Set the color of the shadow to Black.
Color myShadowColor = new Color();
myShadowColor.ScA = 1;
myShadowColor.ScB  = 0;
myShadowColor.ScG  = 0;
myShadowColor.ScR  = 0;
myDropShadowEffect.Color = myShadowColor;

// Set the direction of where the shadow is cast to 320 degrees.
myDropShadowEffect.Direction = 320; 

// Set the depth of the shadow being cast.
myDropShadowEffect.ShadowDepth = 25; 

// Set the shadow softness to the maximum (range of 0-1).
myDropShadowEffect.Softness = 1;
// Set the shadow opacity to half opaque or in other words - half transparent.
// The range is 0-1.
myDropShadowEffect.Opacity = 0.5; 

// Apply the bitmap effect to the Button.
myButton.BitmapEffect = myDropShadowEffect; 



回答2:


The accepted answer is now obsolete. Now you may use:

UIElement uie = ...
uie.Effect = 
    new DropShadowEffect
    {
        Color = new Color {A = 255, R = 255, G = 255, B = 0},
        Direction = 320,
        ShadowDepth = 0,
        Opacity = 1
    };

To achieve the exact same effect as the accepted answer.




回答3:


@Gleno's answer helped me the most. In my case I was using it for visual feedback on a missed form item. To then remove the dropshadow I used:

myComboBox.ClearValue(EffectProperty);

in a selectionChanged event.

Hope this helps someone. I had to search for a bit.



来源:https://stackoverflow.com/questions/4022746/wpf-add-a-dropshadow-effect-to-an-element-from-code-behind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!