Silverlight 3 - 数据绑定画布上矩形的位置 [英] Silverlight 3 - Data Binding Position of a rectangle on a canvas
问题描述
我正在尝试使用ItemsControl将一组对象绑定到Silverlight 3中的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>
不幸的是,似乎Canvas.Left上的绑定被忽略。从我所学到的这里将会出现这是由于项目被放置在内容演示者内,而不是我在项目面板中指定的实际画布。
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?
推荐答案
我意识到这已经有一个答案被接受了,但实现初始目标而不弄乱利润的方式是创建一个自定义的ItemsControl并覆盖PrepareContainerForItemOverride方法。在这种方法中,您可以在代码中设置绑定。
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);
}
}
这篇关于Silverlight 3 - 数据绑定画布上矩形的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!