www.planet-xaml.net
[XAMLWPF]

Binding Position Data to an ItemsHost for Layout

by Florian Krüsch July 21, 2008

Edit: Actually Dr.WPF already showed what I was trying to explain here at the end of this post.

Dr.WPF has added another awesome episode to his continuing ItemsControl saga.

In the Bonus section he explains how to bind to the ItemContainer from within the ItemTemplate. This reminded me of something... from time to time I ran into the need for exactly the opposite thing: binding to the Item itself from within the ItemContainer.

The scenario I'm talking about is when the list item contains some kind of position information and you want that to influence the ItemContainer's layout position within the ItemsHost.

That is, you want a ListBoxItem to show at a position that comes from the object it displays.

Here's a simple solution:

Sample data:
C#toggle
theListBox.ItemsSource = new[]
{
    new { Title = 
"Hello", Pos = new Point(200,30) },
    new { Title = 
"World", Pos = new Point(100,60) }
};

XAML:
XAMLtoggle
<ListBox x:Name="theListBox" Width="240" Height="300" Background="Black">
    
    
<ListBox.ItemTemplate>
        
<DataTemplate>
            
<TextBlock Text="{Binding Title}" Background="Pink" />
        
</DataTemplate>
    
</ListBox.ItemTemplate>
    
    
<ListBox.ItemsPanel>
        
<ItemsPanelTemplate>
            
<Canvas />
        
</ItemsPanelTemplate>
    
</ListBox.ItemsPanel>
    
    
<ListBox.ItemContainerStyle>
        
<Style>
            
<Setter Property="Canvas.Left" Value="{Binding Pos.X}" />
            
<Setter Property="Canvas.Top" Value="{Binding Pos.Y}" />
        
</Style>
    
</ListBox.ItemContainerStyle>
</
ListBox>

Cheers,
Florian

 

No comments

Language | Sprache

All[e]  |  english  |  deutsch
Tags
 

Profile

Florian Kruesch

I am working as a freelance software architect, developer and consultant in Düsseldorf, Germany.

My focus is on Microsoft technologies and .NET 3.0, especially WPF, ASP.net and SQL Server.

I've been a lead programmer on the WPF development of the OTTO Vista Store at SinnerSchrader Studios.

My client list includes DHL, LG and Ogilvy Interactive.