如何以编程方式设置图像源

Kor*_*tak 35 c# silverlight image code-behind

当Image的Source属性按以下方式设置时,图片取自/Images/down.png.

我如何以编程方式执行相同的操作?

<Image x:Name="myImg" Source="/MyProject;component/Images/down.png" />
Run Code Online (Sandbox Code Playgroud)

以下操作无效,因为Image.Source属性不是字符串类型.

myImg.Source = "/MyProject;component/Images/down.png"; 
Run Code Online (Sandbox Code Playgroud)

Chr*_*ant 68

试试这个:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
Run Code Online (Sandbox Code Playgroud)

  • 然后:myImg.Source = image; 如果指定绝对路径,请记住将其设置为UriKind.Absolute. (5认同)

Anj*_*han 10

myImg.Source = new BitmapImage(new Uri(@"component/Images/down.png", UriKind.RelativeOrAbsolute)); 
Run Code Online (Sandbox Code Playgroud)

不要忘记将Build Action设置为"Content",将Copy to output目录设置为"Always".


小智 5

尝试以这种方式分配图像:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));
Run Code Online (Sandbox Code Playgroud)