如何使用 C# 更改 image.source?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17595369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:58:28  来源:igfitidea点击:

How can I change image.source with C#?

c#windows-phone-8

提问by thefriend

I'm developing a Windows Phone app.I have an image . This is its XAML code:

我正在开发 Windows Phone 应用程序。我有一个图像。这是它的 XAML 代码:

<Image x:Name="imageclock" Grid.Row="1" 
        Source="Image/Myimage.png" Height="240" Width="240"
        />

And i want change image.source with this code:

我想用以下代码更改 image.source:

private void ClickonBtn(object sender, EventArgs e)
    {
            BitmapImage bm = new BitmapImage(new Uri("Image/Darktheme.png", UriKind.RelativeOrAbsolute));
            imageclock.Source = bm;
    }

But when i complied, imageclock.Source=Null and this is error:

但是当我遵守时, imageclock.Source=Null 这是错误:

An exception of type 'System.NullReferenceException' occurred in Newappver1.DLL but was not handled in user code

Newappver1.DLL 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理

采纳答案by 3wic

Your code looks ok but maybe you need to add @before the image path to handle the /in the code behind like this :

您的代码看起来不错,但也许您需要@在图像路径之前添加以处理/后面的代码,如下所示:

BitmapImage bm = new BitmapImage(new Uri(@"Image/Darktheme.png", UriKind.RelativeOrAbsolute));