2011-08-24 53 views
25

我有使用數據綁定在畫布中顯示的項目列表。如何通過綁定在畫布中顯示項目

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是汽車性能的簡單類的文字,top和left值

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

當我數據綁定的物品,但會出現在畫布上。但是這些項目不會出現在使用Top和Left屬性提及的位置上。

<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> 
+2

的ItemsControl的TextBlock使用StackPanel的默認itemspanel。您添加的文本塊實際上是添加到堆疊面板,但不添加到畫布。 ItemsControl正在添加到畫布上。嘗試更改項目面板到畫布 – Bathineni

+0

感謝您的答案bathineni。我試圖把ItemsPanel作爲Canvas,但它沒有工作。項目開始顯示一個在另一個上。添加ItemContainerStyle工作。的 –

+0

可能重複[WPF:是否有可能在XAML畫布的兒童屬性綁定?](http://stackoverflow.com/questions/889825/wpf-is-it-possible-to-bind-a-canvass-children -property-in-xaml) –

回答

37

設置ItemsPanelCanvas並綁定容器,而不是在DataTemplate

<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> 
+0

如果我有'Shape'而不是'TextBlock',我可以簡單地替換一個嗎? – IAbstract

+0

另外,'ItemsControl'駐留在文檔樹中? – IAbstract

+0

ItemsControl.ItemsContainerStyle正是我所需要的,其餘的工作。謝謝一堆。 – Grenter

相關問題