Search code examples
wpfxamldata-bindingcollectionsitemscontrol

Databinding of observablecollection in wpf and fill the gui in a special order


I'm trying to create my gui as much with databinding as possible. There for I have collection of channels which also have list of steps. What I know want is to bind those collections to xaml elements and get them displayed in the following order:

Channel1 step1 step2 step3 step4
Channel2 step1 step2 step3 step4

I tried it with nested ItemsControls like this:

<ItemsControl ItemsSource="{Binding Path=channels}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <ItemsControl ItemsSource="{Binding Path=steps}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                             <GUI:stepAnalog></GUI:stepAnalog>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

But all I achieved is something like ordering the elements like:

channel1 step1 step2 step3 channel2 step1 step2 step3

or

channel1
step1
step2
step3
channel2
step1
step2
step3

Is there a solution in wpf with just using databindings or do I have to do it programmatically by iterating over the elements and place them?


Solution

  • Theres always a solution, its just a matter of finding the right one!

    I would suggest playing with the ItemsPanel of you ItemsControls like so:

    <ItemsControl ItemsSource="{Binding Path=channels}"> 
            <!-- This specifies that the items in the top level items control should be stacked vertically-->
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Vertical"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate> 
        <DataTemplate> 
                <ItemsControl ItemsSource="{Binding Path=steps}"> 
                    <!-- This specifies that the items in the second level items control should be stacked horizontally-->
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal" />
                        </ItemsPanelTemplate>               
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate> 
                         <DataTemplate> 
                             <GUI:stepAnalog></GUI:stepAnalog> 
                        </DataTemplate> 
                    </ItemsControl.ItemTemplate> 
                </ItemsControl> 
        </DataTemplate> 
    </ItemsControl.ItemTemplate> 
    

    This allows you to specify how the items in the items control are layed out, and you can still use your DataTemplate to define how they are displayed