图像源UriKind

我有一个项目,它的名字是’xx’。 我创建了一个具有此路径的文件夹“images”:xx \ bin \ Debug \ images \

图像只包含一张照片,其名称为“1.jpg”,MainWindow包含图像控件; 我设置此代码加载图像源但它不起作用为什么??:

private void Image_MouseDown(object sender, MouseButtonEventArgs e) { Image i = sender as Image; ; BitmapImage b = new BitmapImage(new Uri(@"images\1.jpg",UriKind.Relative)); i.Source=b; } 

如何通过代码加载图像源? 提前致谢 :)

您需要在images文件夹中将1.jpg添加到项目中,并将1.jpg 属性设置为Resource 。 要加载资源,请使用packURI约定。

 private void Image_MouseDown(object sender, MouseButtonEventArgs e) { Image i = sender as Image; ; BitmapImage b = new BitmapImage(new Uri(@"pack://application:,,,/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/" + "Images/1.jpg", UriKind.Absolute)); i.Source=b; } 

试试这个

 public void Image_MouseDown(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.InitialDirectory = "c:\\"; dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*"; dlg.RestoreDirectory = true; Nullable result = dlg.ShowDialog(); if (result == true) { BitmapImage bitmap = new BitmapImage(); Image img = sender as Image; bitmap.BeginInit(); bitmap.UriSource = new Uri(dlg.FileName); bitmap.EndInit(); img.Source = bitmap; } }