I'm creating a drag and drop enabled application and I've been trying to use the ItemsControl for binding instead of adding my controls by default. The Displayer is a UserControl that represents the object I'm working with.
ZExtender has a ZIndex, Top, Left, etc properties. The implementation bellow works for the top, left, width correctly, but the ZIndex changes don't take effect. I want binding or changing the ZIndex in code to automatically change it in the UI. Is this possible without using messaging to the codeBehind of my page?
<Border BorderBrush="Black" BorderThickness="2" Margin="35" HorizontalAlignment="Center" VerticalAlignment="Center">
<Canvas AutomationProperties.AutomationId="designerCanvas" Width="{Binding Root.Width}" Height="{Binding Root.Height}">
<Canvas.Background>
<ImageBrush ImageSource="/SilverlightImages/canvasBackground.png" Stretch="None" />
</Canvas.Background>
<ItemsControl ItemsSource="{Binding Containers}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<canvas> <!-- canvas is needed for the positioning to work -->
<controls:Displayer DataContext="{Binding ZExtender}"
Canvas.Top="{Binding Top}"
Canvas.Left="{Binding Left}"
Canvas.ZIndex="{Binding ZIndex}"
Width="{Binding WidthInPixels}"
Height="{Binding HeightInPixels}"
/>
</canvas>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Canvas>
</Border>
I am surprised the Top/Left properties work. The Canvas looks at it's direct children for the Top/Left/ZIndex attached properties. Given a non-UIElement object, the Canvas will wrap the item in a ContentPresenter (which becomes the direct child of the Canvas). So the Canvas will look at the ContentPresenter, not your ZExtender or Displayer controls.
The Displayer control will be created and added as a child of the ContentPresenter. But that is independent of the Canvas.
Normally, you'd need to do something like:
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding Left}" />
<Setter Property="Canvas.Top" Value="{Binding Top}" />
<Setter Property="Canvas.ZIndex" Value="{Binding ZIndex}" />
</Style>
</ItemsControl.ItemContainerStyle>
But Silverlight 4 does not support bindings in Setters like that. So you have to apply the bindings in the code behind. Preferably in the PrepareContainerForItemOverride.
Or you can try the workaround described here.