WPF动态创建Image的显示问题

原文: WPF动态创建Image的显示问题

最近学习WPF,看到一篇教程讲解如何动态创建Image控件,自己练手时候无论如何也显示不出图片。刚开始以为是图片的路径有问题,可后来将图片的路径设为相对路径或者绝对路径都没有解决问题。于是开始在网上搜索资料,直到发现一篇问答《WPF用Image显示图片失误(为啥显示不出来)》,才从回答中找出答案,直接贴代码:

编程环境:VS2012

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("Resource/0.png", UriKind.RelativeOrAbsolute);
            bi.EndInit();
            bi.Freeze();

            Image image = new Image();
            image.Source = bi;

            image.Width = imageWidth;                       //设置图片宽度
            image.Height = imageHeight;                     //设置图片高度
            image.SetValue(Canvas.LeftProperty, imageLeft); //设置图片x坐标
            image.SetValue(Canvas.TopProperty, imageTop);   //设置图片y坐标
            canvas_main.Children.Add(image);                //将图片添加到canvas容器中


猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/10167842.html