Search code examples
wpfwpf-controlsitemscontrol

Display items WPF


I need to display a cards game board. My BoardViewModelM exposes an IEnumerable where the CardViewModel has the information where the card should be drawn on the board. I would like the baord to:

  • Use all available size to draw the cards (scaling the location and size data provided by the cards, keeping proportions)
  • Support zooming (including gestures zooming)

I was considering:

  • create a custom ItemsControl (how?) and create a custom panel.
  • Iterate on the collection and dynamically create a control for each one to place on a canvas (seems a bit crude)

What should be my course of action?


Solution

  • I would use binding to display your card collection - one option is to use an ItemsControl with a Canvas as the ItemsPanel, and set the ItemContainerStyle to position each card. Something like:

    <ItemsControl ItemsSource="{Binding CardCollection}">
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
          <Canvas />
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
        <DataTemplate>
          <Image Source="{Binding CardImage}" Width="{Binding CardWidth}" Height="{Binding CardHeight}" />
        </DataTemplate>
      </ItemsControl.ItemTemplate>
      <ItemsControl.ItemContainerStyle>
        <Style>
          <Setter Property="Canvas.Left" Value="{Binding CardX}" />
          <Setter Property="Canvas.Top" Value="{Binding CardY}" />                    
        </Style>
      </ItemsControl.ItemContainerStyle>
    </ItemsControl>