将 ObservableCollection(Of T) 绑定到 Canvas (3)

书接上回,话说为了模仿 Bubble 脑图,费劲心思将Node对象绑定到Canvas上,

实现简单的Left Top 定位。采用了ItemsContorl 装 Canvas的方式。不曾想

虽然装入,并不能使用Canvas.Left 和 Canvas.Top 属性来定位Node。

imageimage

如果想要定位Node的具体位置,还要加入<ControlTemplate>和<ItemsControl.ItemContainerStyle>

代码如下

1 <ItemsControl.Template> 2 <ControlTemplate TargetType="{x:Type ItemsControl}"> 3 <ItemsPresenter/> 4 </ControlTemplate> 5 </ItemsControl.Template> 6 <ItemsControl.ItemContainerStyle> 7 <Style TargetType="{x:Type ContentPresenter}"> 8 <Setter Property="Canvas.Left" 9 Value="{Binding Path=Left}"></Setter> 10 <Setter Property="Canvas.Top" 11 Value="{Binding Path=Top}"></Setter> 12 </Style> 13 </ItemsControl.ItemContainerStyle>

并且,将Left和Top属性绑定在Setter上。

这时再定义Left和Top属性,效果就出来了。

image

完整的Xaml代码如下

1 <Window x:Class="MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:ct="clr-namespace:AMindMapControls;assembly=AMindMapControls" 5 Title="MainWindow" Height="350" Width="525"> 6 <Grid> 7 <ItemsControl ItemsSource="{Binding NodeList}"> 8 <ItemsControl.Template> 9 <ControlTemplate TargetType="{x:Type ItemsControl}"> 10 <ItemsPresenter/> 11 </ControlTemplate> 12 </ItemsControl.Template> 13 <ItemsControl.ItemContainerStyle> 14 <Style TargetType="{x:Type ContentPresenter}"> 15 <Setter Property="Canvas.Left" Value="{Binding Path=Left}"></Setter> 16 <Setter Property="Canvas.Top" Value="{Binding Path=Top}"></Setter> 17 </Style> 18 </ItemsControl.ItemContainerStyle> 19 <ItemsControl.ItemTemplate> 20 <DataTemplate> 21 <ct:ANode Text="{Binding Text}" Left="{Binding Left}" Top="{Binding Top}"/> 22 </DataTemplate> 23 </ItemsControl.ItemTemplate> 24 <ItemsControl.ItemsPanel> 25 <ItemsPanelTemplate> 26 <Canvas/> 27 </ItemsPanelTemplate> 28 </ItemsControl.ItemsPanel> 29 </ItemsControl> 30 <Button Canvas.Left="386" Canvas.Top="278" Content="Button" Height="23" Name="Button1" Width="75" /> 31 </Grid> 32 </Window> 33

至此,关于集合绑定到Canvas,就告一段略了,稍后,写一个详细的开发过程。

原文地址:https://www.cnblogs.com/allofalan/p/2433207.html