Introduction
This is a very simple class to apply and remove blur effect on UIElement
in WPF.
Using the Code
You have only two extension methods: BlurApply
and BlurDisable
. The first one is called before applying effect - for example before showing dialog. The second one is usually called in finally
block to guarantee returning to normal view even if exception occurred.
try
{
this.BlurApply(BlurRadius, new TimeSpan(0, 0, 1), TimeSpan.Zero);
MessageBox.Show("Test");
}
finally
{
this.BlurDisable(new TimeSpan(0, 0, 5), TimeSpan.Zero);
}
Also, you can apply this to any UIElement
, like this TextBlock
:
try
{
txt.BlurApply(BlurRadius, new TimeSpan(0, 0, 1), TimeSpan.Zero);
MessageBox.Show("Test");
}
finally
{
txt.BlurDisable(new TimeSpan(0, 0, 5), TimeSpan.Zero);
}
The source code is as follows:
public static class BlurElementExtension
{
public static void BlurApply(this UIElement element,
double blurRadius, TimeSpan duration, TimeSpan beginTime)
{
BlurEffect blur = new BlurEffect() { Radius = 0 };
DoubleAnimation blurEnable = new DoubleAnimation(0, blurRadius, duration)
{ BeginTime = beginTime };
element.Effect = blur;
blur.BeginAnimation(BlurEffect.RadiusProperty, blurEnable);
}
public static void BlurDisable(this UIElement element, TimeSpan duration, TimeSpan beginTime)
{
BlurEffect blur = element.Effect as BlurEffect;
if (blur == null || blur.Radius == 0)
{
return;
}
DoubleAnimation blurDisable = new DoubleAnimation(blur.Radius, 0, duration) { BeginTime = beginTime };
blur.BeginAnimation(BlurEffect.RadiusProperty, blurDisable);
}
}
Thank you!