例如,我要绑定一个员工的图片信息
//员工信息
private void Select_StaffMassage() {
string SImg = Convert.ToString(Application.Current.Properties["SImg"]);
IDStaffImg.ImageSource = _10Base.BindingImg.GetImage(System_Path + "_08Server_Img//Simages//" + SImg);
}
class BindingImg
{
//释放资源
public static BitmapImage GetImage(string imagePath)
{
BitmapImage bitmap = new BitmapImage();
if (File.Exists(imagePath))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
{
bitmap.StreamSource = ms;
bitmap.EndInit();
bitmap.Freeze();
}
}
else
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
string System_ = System.AppDomain.CurrentDomain.BaseDirectory + "_08Server_Img//Simages//V_02.png";
using (Stream ms = new MemoryStream(File.ReadAllBytes(System_)))
{
bitmap.StreamSource = ms;
bitmap.EndInit();
bitmap.Freeze();
}
}
return bitmap;
}
}
我们需要提前准备一张图片放在程序中,当找不到员工图片时,有一张图片替换,而不是报错,放在bin目录下