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
443 views
in Technique[技术] by (71.8m points)

c# - Silverlight 3 - Data Binding Position of a rectangle on a canvas

I am currently trying to bind a collection of objects to a Canvas in Silverlight 3 using an ItemsControl as below:

<ItemsControl x:Name="ctrl" ItemsSource="{Binding myObjectsCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas></Canvas>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Rectangle Stroke="LightGray" Fill="Black"  StrokeThickness="2" 
                   RadiusX="15" RadiusY="15" Canvas.Left="{Binding XAxis}"
                   Height="25" Width="25">
            </Rectangle>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Unfortunately it seems the binding on the Canvas.Left is being ignored. From what i have learned here it would appear this is due to the items being placed inside a content presenter not the actual canvas i have specified in the items panel.

Is there a way i can use data binding to determine the position of elements on a canvas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I realize that this already has an answer accepted, but the way to achieve the initial goal without messing with margins is to create a custom ItemsControl and override the PrepareContainerForItemOverride method. In this method, you set the binding in code.

public class CustomItemsCollection
    : ItemsControl
{
    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {

        FrameworkElement contentitem = element as FrameworkElement;
        Binding leftBinding = new Binding("Left"); // "Left" is the property path that you want to bind the value to.
        contentitem.SetBinding(Canvas.LeftProperty, leftBinding);

        base.PrepareContainerForItemOverride(element, item);
    }

}

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

...