WPF: Working with Opacity Animation Programmatically (without xaml)
using System.Windows.Media.Animation;
using System.Windows.Controls;
using System.Windows.Media;
...
private DoubleAnimation daOpacity;
private Storyboard sbOpacity;
private Image imgSample;
public void opacityAnimation()
{
// loading image
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.UriSource = (new Uri(@"C:\temp\myImg.jpg"));
myBitmapImage.EndInit();
imgSample = new Image();
imgSample.Source = myBitmapImage;
this.Children.Add(imgBack);
// end of loading image
// make a new namescope
NameScope.SetNameScope(this, new NameScope());
// register Image's name
RegisterName("_sampleImage", imgSample);
// make a new DoubleAnimation Object which will change opacity
daOpacity = new DoubleAnimation();
// set target
Storyboard.SetTargetName(daOpacity, "_sampleImage");
Storyboard.SetTargetProperty(daOpacity, new PropertyPath(Control.OpacityProperty));
sbOpacity = new Storyboard();
sbOpacity.Children.Add(daOpacity);
// now, we are ready to animate opacity
// set DoubleAnimation properties
daOpacity.From = 1;
daOpacity.To = 0;
daOpacity.Duration = new Duration(TimeSpan.FromMilliseconds(500));
// begin animation
sbOpacity.Begin(this);
}
This is the way to control opacity of dyanmically-generated object through DoubleAnimation in your code (not XAML Tag)
Actually, There is a lot of articles about WPF animation, but
I couldn't find about animating opacity progrmmactically.
I tried many ways to find out solution, and made a lot of wastes,..
And finally I happened to make this solution today.
So I want to share my code so that you can save your time.
The most important thing is, register your control to namespace
so that StoryBoard can find the control without any "Name" tag of Xaml.
(Because you don't want to use Xaml)
Like this: RegisterName("_sampleImage", imgSample);
코드상에서 Dynamic 하게 생성한 개체에 대해, Programmatic한 방법으로 Opacity를 애니메이션 하는 코드입니다.
영어도 지지리 못하는 주제에 굳이 재수없게 제목을 영어로 단 이유는,
(게다가 말도 안되는 영어 설명까지 취한 상태에서 붙인 이유는 -_-;;)
제가 며칠을 구글, MSDN, 네이버를 뒤졌는데, 한글은 물론 영어로 된 비슷한 문서 하나 찾을 수 없었기 때문에, 삽질들 하지 마시라는 의미에서 영어로 걸었습니다.
설명은 한글이더라도, 제목이 영어면 필요하신분들이 찾아서들 오지 않을까 해서요.
사실 국내엔 WPF 하시는 분이 크게 없는 것 같고..
설명은 대부분 주석에 되어 있습니다만,
가장 중요한 부분만 말하자면, control을 namespace에 등록하는 것입니다
(translate, rotate, scale 등에서 transformation object를 등록하는 것과 다르다는 점이 가장 큰 차이입니다)
이렇게요: RegisterName("_sampleImage", imgSample);
이렇게 해 두면, XAML의 Name 태그 없이, 코드 상에서 만든 개체에 대해서 컨트롤이 가능합니다.
코드는 제한없이 사용하셔도 되고, 트랙백도 환영합니다.
하지만 고대로 긁어다가 자기 것인양 하시면 화낼겁니다.
별 것 아닌 거지만 고민 좀 했거든요.