3

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

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

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;
}

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

4

2 回答 2

2

您需要添加1.jpgimages文件夹中的项目并将 Properties1.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;
}
于 2012-05-18T14:55:56.907 回答
0

尝试这个

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<bool> 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;
    }
}
于 2012-05-23T06:22:31.023 回答