Binding A List of Images

穿精又带淫゛_ 提交于 2020-01-07 03:47:39

问题


I was trying to bind a list of images (List) to a StackPanel, I tried to separate those Images by using <Separator> but sadly it's not working. Anyone has a clue why? (i'm kinda rookie on wpf..so sry)

My Code: Code Behind:

            List<Image> v2 = new List<Image>();
        for (int i = 0; i < 10; i++)
        {
            Image v2image = new Image();
            v2image.BeginInit();

            v2image.Source = new BitmapImage(new Uri("http://static.lolskill.net/img/champions/64/xayah.png"));
            v2image.Width = 40;
            v2image.Height = 40;
            v2.Add(v2image);
        }

        BlueTeam.ItemsSource = v2;

The XAML:

<Window x:Class="FML.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:FML"
    mc:Ignorable="d"
    Title="MainWindow" Height="525.885" Width="809.974">
<Grid>
    <ItemsControl Grid.Column="0" x:Name="BlueTeam">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" >

                </StackPanel>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical" >
                    <Image Source="{Binding v2image.Source}"></Image>
                    <Separator Opacity="0" Height="20" Width="20"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>   
    </ItemsControl>
</Grid>

Ty for helping me :D btw: The Images are very small aswell. they're not 40 Width\Height

edit: This is how it supposed to work: http://imgur.com/a/bZbLf (It works when I'm using a class who has only Image)

this is how it works: http://imgur.com/a/uptlo


回答1:


You should not have a List<Image>, but a List<ImageSource> instead:

var v2 = new List<ImageSource>();

for (int i = 0; i < 10; i++)
{
    v2.Add(new BitmapImage(
        new Uri("http://static.lolskill.net/img/champions/64/xayah.png")));
}

BlueTeam.ItemsSource = v2;

You would then declare an Image control with a fixed size in the ItemTemplate and bind it directly to the collection element, by Source="{Binding}":

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Image Source="{Binding}" Width="40" Height="40" Margin="10"/>
    </DataTemplate>
</ItemsControl.ItemTemplate>   

Not sure what the Separator was supposed to do. In the example above, I've simply set the Image's Margin property.



来源:https://stackoverflow.com/questions/44460018/binding-a-list-of-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!