简体   繁体   English

通过C#更改XAML中的图像源

[英]Changing the Source of an Image in XAML through C#

So I have a Grid name Game (the main game board) what I wanna do is load every image from inside the grid when the program loads 所以我有一个名为Grid的游戏(主游戏板),我想要做的是在程序加载时从网格内部加载每个图像

foreach(Image myImage in Game.Children)
            {
                BitmapImage bi3 = new BitmapImage();
                bi3.UriSource = new Uri("ms-appx:///Assets/SmallLogo.png");
                myImage.Stretch = Stretch.Fill;
                myImage.Source = bi3;
            }

I am using this foreach but I always get error messages. 我正在使用此foreach,但总是收到错误消息。 I tried a lot of different methods but none worked so far. 我尝试了许多不同的方法,但到目前为止都没有奏效。 I am trying to make a matching memory game. 我正在尝试制作匹配的记忆游戏。 Thanks in advance 提前致谢

The child of your Grid is a StackPanel, not the Image itself. Grid的子级是StackPanel,而不是Image本身。 You'll probably need to dig in deeper to the StackPanel. 您可能需要更深入地研究StackPanel。 If you share your XAML too it'll be easier to tell, but I'm guessing the Images are something like the datacontext of the one of the contents in your StackPanel. 如果您也共享XAML,则更容易分辨,但是我猜想Images就像StackPanel中内容之一的datacontext一样。

Share the XAML if you're still running into issues 如果仍然遇到问题,请共享XAML

After checking XAML you provided on jack's answer the problem is pretty obvious. 在检查了XAML之后,您在jack的答案中提供了该问题,非常明显。 You are iterating over all of the children of the Grid and implicitly casting them to Image but one of the child is a StackPanel and that is where your exception occurs. 您正在遍历Grid的所有子级,并将它们隐式转换为Image,但是其中一个是StackPanel,这就是发生异常的地方。 You should first check if that children is the Image: 您应该首先检查孩子是否是图像:

foreach (var child in Game.Children)
{
    var myImage = child as Image;
    if (myImage == null)
    {
        continue;
    }
    BitmapImage bi3 = new BitmapImage();
    bi3.UriSource = new Uri("ms-appx:///Assets/SmallLogo.png");
    myImage.Stretch = Stretch.Fill;
    myImage.Source = bi3;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM