seanzi
seanzi

Reputation: 883

Binding Converter using index of item in list

I have a scenario which requires me to bind a list of objects to a grid. I would like the behaviour as such that :-

• When an item is added to the list it moves to the next available space in the grid. (like a wrap panel)

Shown below is my current XAML.

<ItemsControl ItemsSource="{Binding Path=Contents}" Grid.Row="1">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <cc:DynamicGrid ShowGridLines="True" RowCount="{Binding Path= SelectedGridStyle.RowCount}" ColCount="{Binding Path=SelectedGridStyle.ColCount}"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel> 
</ItemsControl>

Currently this puts all of the items on top of each other because I have not specified a row index or column index. I plan to add the following to rectify this

 <ItemsControl.ItemContainerStyle>
     <Style>
         <Setter Property="Grid.Column" Value="{Binding Path=ColumnIndex}"/>
         <Setter Property="Grid.Row" Value="{Binding Path=RowIndex}"/>
         <Setter Property="Grid.ColumnSpan" Value="{Binding Path=ColumnSpan}"/>
         <Setter Property="Grid.RowSpan" Value="{Binding Path=RowSpan}"/>
     </Style>
 </ItemsControl.ItemContainerStyle>

I have the following code which will allow me to calculate the rowIndex and columnIndex from the index in the list.

int m_ColumnCount = 3;
int rowIndex = index / m_ColumnCount;
int columnIndex = index - (rowIndex * m_ColumnCount);

I am attempting to create a binding converter using the above to set these values. However this calculation depends on values held in the view model for the number of columns and rows. Is there a way to get these values?Can the above be achieved or is there a better solution?

Upvotes: 0

Views: 1502

Answers (2)

Kenn
Kenn

Reputation: 2769

Check out this - http://www.switchonthecode.com/tutorials/wpf-tutorial-using-multibindings

You will see about half way down the use of the multibinding, it's pretty simple. Then they show you how to create a converter for it. Sounds like you are familiar with converters so I think that article will get you moving.

Upvotes: 1

brunnerh
brunnerh

Reputation: 185445

If a binding needs more than one value you could use a MultiBinding. To bind to the main viewmodel you can use a RelativeSource targeting the ItemsControl.

Upvotes: 1

Related Questions