Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

c# - How to display items in Canvas through Binding

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 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; }
}

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...