WPF图片切换问题(美女时钟)

最近想弄个基于WPF的美女时钟,主要思想就是一个Image控件显示图片,添加一个Timer定时设置每秒更新一张图片。在弄的过程中发现一些小问题,在这里记下来留着以后查看!

  1:设置Iamge的Source属性的时候,在前台Xaml文件可以设置为路径的字符串格式,但是在后台cs文件需要构造一个Bitmap的实例赋值给Image的Source属性,还要注意实例化Uri类的时候需要传进来一个UriKind.Relative的枚举。如下:

        DateTime dtNowTime = DateTime.Now.ToLocalTime();
            //获取要加载的图片的名称
            string imgFileName = dtNowTime.Minute.ToString("00") + "_" + dtNowTime.Second.ToString("00") + ".jpg";
            BitmapImage bmpImage= new BitmapImage(new Uri("/Images/" + imgFileName, UriKind.Relative));
            imgMM.Source = bmpImage;

 2:实现图片每秒更新的时候,需要注意不能用一个timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);事件直接实现更新,会报出“调用线程无法访问此对象,因为另外一个线程拥有此对象”的异常。

这时的解决方案是定义一个委托,用异步Dispatcher.Invoke()实现!项目的后台代码如下:

/// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private delegate void TimerDispatcherDelegate();
        public MainWindow()
        {
            InitializeComponent();
        }
        Timer timer = null;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            timer = new Timer();
            timer.Interval = 1000;
            timer.Enabled = true;
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.Dispatcher.Invoke(DispatcherPriority.Normal, new TimerDispatcherDelegate(UpdataImage));
        }
        /// <summary>
        /// 更新图片
        /// </summary>
        void UpdataImage()
        {
            DateTime dtNowTime = DateTime.Now.ToLocalTime();
            //获取要加载的图片的名称
            string imgFileName = dtNowTime.Minute.ToString("00") + "_" + dtNowTime.Second.ToString("00") + ".jpg";
            //获取当前应用程序的根路径
            string rootPath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName.ToString();
            BitmapImage bmpImage= new BitmapImage(new Uri("/Images/" + imgFileName, UriKind.Relative));
            imgMM.Source = bmpImage;
        }
        
    }

 其中图片位于根路径下的Image文件夹中,imgMM为前台页面中Image控件的Name

原文地址:https://www.cnblogs.com/xiexingen/p/3037555.html