如何通过绑定在 Canvas 中显示项目 [英] How to display items in Canvas through Binding

查看:32
本文介绍了如何通过绑定在 Canvas 中显示项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have list of items that I want to display in Canvas using data binding.

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 值的自动属性

ItemDetail is a simple class with auto properties for Text, Top and Left values

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

当我对项目进行数据绑定时,它们确实出现在画布中.但是这些项目不会出现在使用 Top 和 Left 属性提到的位置.

When I databind the items, they do appear in canvas. But the items do not appear at positions mentioned using Top and Left properties.

<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 并绑定容器而不是 TextBlockDataTemplate

Set the ItemsPanel to a Canvas and bind the containers instead of the TextBlock in the 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>

这篇关于如何通过绑定在 Canvas 中显示项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆