如何为图像做数组?

时间:2013-07-25 08:33:48

标签: c# wpf arrays xaml

我有20张图片,它们是ball1,ball2,...,ball20。

据说,我使用

插入图像 .xaml中的

Image x:Name="ball1" Source="/Images/ball1.png" Canvas.Left="150" Canvas.Top="200"

目前,我试图以这种方式插入

Uri uri = new Uri("/Images/ball1.png", UriKind.Relative);
ImageSource img = new System.Windows.Media.Imaging.BitmapImage(uri);
image.SetValue(Image.SourceProperty, img);
cv.Children.Add(image);

但是,我无法以这种方式使用它,因为它没有指定我想要插入它的位置。

我想通过.xaml避免这样做,我怎样才能在.cs中使用数组呢?

2 个答案:

答案 0 :(得分:0)

您可以在XAML中声明Image个对象,然后根据您的代码更新Source属性或查看模型(如果您愿意)。对于此方法,您需要在视图模型或代码后面的每个图像中使用一个属性:

public string Image1SourcePath
{
    get { return image1SourcePath; }
    set { image1SourcePath = value; NotifyPropertyChanged("Image1SourcePath"); }
}
...
public string Image20SourcePath
{
    get { return image20SourcePath; }
    set { image20SourcePath = value; NotifyPropertyChanged("Image20SourcePath"); }
}

确保您实施某种形式的INotifyPropertyChanged界面

<Image Source="{Binding Image1SourcePath}" Canvas.Left="150" Canvas.Top="200" />
...
<Image Source="{Binding Image20SourcePath}" Canvas.Left="1500" Canvas.Top="200" />

然后在你的视图模型或代码背后:

Image1SourcePath = "/YourApplicationName;component/Images/ball1.png";
...
Image20SourcePath = "/YourApplicationName;component/Images/ball20.png";

这是很多代码,但它允许您从代码中更新Image.Source属性并在XAML中设置位置。

答案 1 :(得分:0)

您可以通过在Canvas类上调用相应的静态方法来设置附加属性(Canvas.Left&amp; Canvas.Top)。

Uri uri = new Uri("/Images/ball1.png", UriKind.Relative);
ImageSource img = new System.Windows.Media.Imaging.BitmapImage(uri);
image.SetValue(Image.SourceProperty, img);
cv.Children.Add(image);

// Position the image on the canvas
Canvas.SetLeft(150);
Canvas.SetTop(200);

如果您要显示的图像列表,您可以执行以下操作:

        List<Uri> imageUris = new List<Uri>() 
        { 
            new Uri(@"C:\Users\Grant\Pictures\Heron_zoomed.png"),
            new Uri(@"C:\Users\Grant\Pictures\bridge.jpg") 
        };

        int left = 20;
        int top = 10;

        foreach (var uri in imageUris)
        {
            Image image = new Image { Source = new BitmapImage(uri) };
            Canvas.SetLeft(image, left);
            Canvas.SetTop(image, top);
            MainCanvas.Children.Add(image);

            left += 400;
        }

上面的代码假设您在窗口xaml中有类似以下内容,并且imageUris列表中的文件名存在。

<Grid>
    <Canvas x:Name="MainCanvas">

    </Canvas>
</Grid>

我不知道您要对这些图片做些什么。如果您只想在网格中显示它们,您可以使用其中一个WPF集合控件来执行此操作而无需任何代码。

执行此操作的一种方法是Displaying images in grid with WPF

我怀疑有更好的选择,但这将是一个开始。