Search code examples
mvvmwpf-controlsbindingclickable-image

How can I make a grid of clickable images from a list of data in WPF?


I am a seasoned C and Java programmer, but an absolute WPF newbie.

I am creating a kiosk application that will display a list of images of products that the user will click to see product details and maybe place an order.

I am trying to structure my app with MVVM Foundation because I am used to the benefits of structure and tests.

I wonder what is the most natural way to create a grid of clickable images that will fill the screen left to right, top to bottom (or the other way round, I have no exact requirements).

Any image should be bound to an object that will become current and be displayed in the next screen. Thanks for your help.


Solution

  • OK! Listen up! Here is how you do that! :) 1) Use ItemsControl together with UniformGrid to get automatic aligment

    <ItemsControl>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid>
                </UniformGrid>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <Button Width="50" Height="50"/>
        <Button Width="50" Height="50"/>
        <Button Width="50" Height="50"/>
    </ItemsControl>
    

    2) Populate ItemsControl with data from your viewmodel

    <ItemsControl ItemsSource="{Binding Path=ImageList}"...
    
    public ObservableCollection<ClickableImage> ImageList
    {
        get { return m_ImageList;}
    }
    
    ... constructor
    {
        m_ImageList = new ObservableCollection<ClickableImage>();
        m_ImageList.Add(new ClickableImage("image.png");
    }
    

    TADAAAA!