Recently, I want to create a WPF-based Dynamic album. The main idea is to display an Image in an Image control and add a Timer to update an Image every second. I found some minor problems during the process. I will keep them here and check them later!
1: when setting the Source attribute of Iamge, the front-end Xaml file can be set to the path string format, but in the background cs file, you need to construct a Bitmap instance and assign it to the Source attribute of the Image, also note that when instantiating the Uri class, you need to upload a UriKind. enumeration of Relative. As follows:
Uri uri = new Uri("/Images/" + curImage,UriKind.Relative); BitmapImage bitmap = new BitmapImage(uri); myImage.Source = bitmap;
2: when updating images per second, you must note that you cannot use a timer. elapsed + = new ElapsedEventHandler (timer_Elapsed); when the event is directly updated, an exception is reported that "The Calling thread cannot access this object because another thread has this object.
In this case, the solution is to define a delegate and implement it with asynchronous Dispatcher. Invoke! As follows:
private delegate void TimerDispatcherDelegate(); private void autoShow_Click(object sender, RoutedEventArgs e) { timer = new Timer(); timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Interval = 1000; timer.Enabled = true; timer.Start(); } void timer_Elapsed(object sender, ElapsedEventArgs e) { this.Dispatcher.Invoke(DispatcherPriority.Normal, new TimerDispatcherDelegate(UpdataImage)); }void UpdataImage() { NextImage(imageList, imageIndex, curImage, uri); }
Main Interface code: http://www.cnblogs.com/PaulMa/admin/Files.aspx