Souvik Basu Souvik Basu - 1 year ago 137
C# Question

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.

<ItemsControl ItemsSource="{Binding Path=ItemsToShowInCanvas}">
<TextBlock Text="{Binding Path=Text}" Canvas.Top="{Binding Path=Top}" Canvas.Left="{Binding Path=Left}"/>

Answer Source

Set the ItemsPanel to a Canvas and bind the containers instead of the TextBlock in the DataTemplate

<ItemsControl ItemsSource="{Binding Path=ItemsToShowInCanvas}">
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding Left}"/>
            <Setter Property="Canvas.Top" Value="{Binding Top}"/>
            <TextBlock Text="{Binding Path=Text}" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download