如何通过绑定在canvas中显示项目

我有使用数据绑定在Canvas中显示的项目列表。

ItemsToShowInCanvas = new ObservableCollection<ItemDetail> { new ItemDetail {Text = "ABC", Top = 10, Left = 200}, new ItemDetail {Text = "DEF", Top = 100, Left = 300}, new ItemDetail {Text = "PQR", Top = 50, Left = 150} }; 

ItemDetail是一个简单的类,具有Text,Top和Left值的自动属性

 public class ItemDetail { public string Text { get; set; } public double Top { get; set; } public double Left { get; set; } } 

当我绑定的项目,他们确实出现在canvas上。 但是这些项目不会出现在使用“上”和“左”属性提及的位置上。

 <Canvas> <ItemsControl ItemsSource="{Binding Path=ItemsToShowInCanvas}"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=Text}" Canvas.Top="{Binding Path=Top}" Canvas.Left="{Binding Path=Left}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Canvas> 

ItemsPanel设置为Canvas然后绑定容器,而不是DataTemplate中的TextBlock

 <ItemsControl ItemsSource="{Binding Path=ItemsToShowInCanvas}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style TargetType="ContentPresenter"> <Setter Property="Canvas.Left" Value="{Binding Left}"/> <Setter Property="Canvas.Top" Value="{Binding Top}"/> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=Text}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>