我有要使用数据绑定在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>
<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>
答案 0 :(得分:44)
将ItemsPanel
设置为Canvas
并绑定容器,而不是TextBlock
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>