按下按钮时更新图像源

本文关键字:图像 更新 按钮 | 更新日期: 2023-09-27 17:57:34

我的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));       
}

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

mscorlib.dll中发生类型为"System.ArgumentException"的异常,但在用户代码中未>处理

如何从代码中设置图像源?

按下按钮时更新图像源

如何实现以下静态类:

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

上面的图片(半衰期.png)是在Content/Obrazky下的bin文件夹中找到的吗?

如果没有,您可能还想将图像属性"复制到输出目录"更改为"始终复制"(将图像添加到项目文件夹时,此属性的默认值为"不复制")。