一尘不染

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

c#

我有要使用数据绑定在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>

阅读 344

收藏
2020-05-19

共1个答案

一尘不染

设置ItemsPanelCanvas和绑定容器,而不是TextBlockDataTemplate

<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>
2020-05-19