Is it possible to bind a Canvas's Children property in XAML?
Solution 1:
<ItemsControl ItemsSource="{Binding Path=Circles}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="White" Width="500" Height="500" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse Fill="{Binding Path=Color, Converter={StaticResource colorBrushConverter}}" Width="25" Height="25" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
<Setter Property="Canvas.Left" Value="{Binding Path=X}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
Solution 2:
Others have given extensible replies on how to do what you actually want to do already. I'll just explain why you couldn't bind Children
directly.
The problem is very simple - data binding target cannot be a read-only property, and Panel.Children
is read-only. There is no special handling for collections there. In contrast, ItemsControl.ItemsSource
is a read/write property, even though it is of collection type - a rare occurence for a .NET class, but required so as to support the binding scenario.