Aishwar
Aishwar

Reputation: 9714

Dynamically create elements and bind them to a List<T>

I have a ObservableCollection<Class1> where Class1 contains x and y positions as properties. The list can be of any size. I have a ViewModel that exposes the collection as a property. In my view, I want to generate a list of elements based on the collection and then set their x and y positions based on the Class1 Object's properties.

How can I do this? I know I can easily bind a collection control (like List View) to the Collection easily. But I need to bind it and the elements use the x, y property to position themselves on the canvas. Any ideas appreciated.

Upvotes: 1

Views: 288

Answers (2)

Damian Schenkelman
Damian Schenkelman

Reputation: 3535

You might be able to use a Collection View or something similar to achieve this.

I hope this helps.

Thanks, Damián

Upvotes: 0

Steve Greatrex
Steve Greatrex

Reputation: 15999

You can use a Canvas as your ItemsPanel in the ItemsControl, and then bind the Canvas.Top and Canvas.Left properties on the ItemContainerStyle to the X and Y properties:

<ItemsControl ItemsSource="{Binding}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>

        <ItemsControl.ItemContainerStyle>
            <Style>
                <Setter Property="Canvas.Left" Value="{Binding X}" />
                <Setter Property="Canvas.Top" Value="{Binding Y}" />
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>

Upvotes: 1

Related Questions