按下按钮时更新图像源

时间:2014-04-09 18:44:05

标签: c# image xaml uri

我的Uri和我的图片文件存在问题。

我测试了许多关于如何使它工作但没有成功的事情。

(我开始时有图像A。我点击图像和图像A更改为B.) 请问有人可以解决这个问题吗? 我知道这里有很多问题,但我还是不明白。 Thx提前

XAML:

<Image x:Name="obr_0_1" Grid.ColumnSpan="1"
Grid.Column="0" Grid.Row="0"
Tapped="obr_0_1_Tapped" Loaded="obr_0_1_Loaded"/>`


C#:

private void obr_0_1_Tapped(object sender, TappedRoutedEventArgs e)
{
   zmenObrazek();
}

private void zmenObrazek()
{
   obr_0_1.Source = new BitmapImage(new Uri("/Content/Obrazky/half-life.png", UriKind.Relative));       
}

当我以这种方式设置源时,我得到:

  

类型&#39; System.ArgumentException&#39;的例外情况发生在mscorlib.dll但不是&gt;用户代码处理

如何从代码设置图像源?

1 个答案:

答案 0 :(得分:0)

如何实现以下静态类:

using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

// I don't know your namespace but put it in the same namespace as your code above
// (or reference this namespace in your code above)
namespace MyNamespace
{
  public static class Helper
  {
    public static Image CreateImage(string fileName, int desiredPixelWidth)
    {
        Image myImage = new Image();
        //set image source
        myImage.Source = CreateSource(fileName);
        myImage.Width = desiredPixelWidth;

        return myImage;
    }

    public static BitmapImage CreateSource(string fileName)
    {
        var file = new FileInfo(fileName);

        System.Drawing.Image im = System.Drawing.Image.FromFile(file.FullName);

        int actualPixelWidth = im.Width;
        Uri fileUri = new Uri(file.FullName);
        // Create source
        BitmapImage myBitmapImage = new BitmapImage();

        // BitmapImage.UriSource must be in a BeginInit/EndInit block
        myBitmapImage.BeginInit();
        myBitmapImage.UriSource = fileUri;

        // To save significant application memory, set the DecodePixelWidth or   
        // DecodePixelHeight of the BitmapImage value of the image source to the desired  
        // height or width of the rendered image. If you don't do this, the application will  
        // cache the image as though it were rendered as its normal size rather then just  
        // the size that is displayed. 
        // Note: In order to preserve aspect ratio, set DecodePixelWidth 
        // or DecodePixelHeight but not both.
        myBitmapImage.DecodePixelWidth = actualPixelWidth;
        myBitmapImage.EndInit();

        return myBitmapImage;
    }
  }
}

然后在源代码中执行以下操作

private void zmenObrazek()
{
   // do you need the first forward slash?
   // (I assume "Content" is a folder in the bin directory)
   obr_0_1.Source = Helper.CreateSource("Content/Obrazky/half-life.png");       
}

在Content / Obrazky下的bin文件夹中找到上面的图像(half-life.png)?

如果不是,您可能还想更改图像属性,复制到输出目录,以及#34;始终复制&#34; (当您将图像添加到项目文件夹时,此属性的默认值为&#34;请勿复制&#34;)。