如何在Canvas中绑定形状/控件的绝对坐标
在Windows 8.1 Metro应用程序上,我尝试将视图模型中的形状集合绑定到MainPage.xaml中.每个形状将具有一个Left
,Top
和一个PathData
,这将是一个RectangleGeometry
,其中包含要在画布内相应位置绘制的矩形.
On a Windows 8.1 Metro app, I'm trying bind a collection of shapes from my view model into MainPage.xaml. Each shape will have a Left
, Top
and also a PathData
which will be a RectangleGeometry
that contains the rectangle that I want drawn inside the canvas at the corresponding position.
这是XAML:
<Grid Background="Black">
<ItemsControl ItemsSource="{Binding Shapes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Path Data="{Binding PathData}" Stroke="White" StrokeThickness="3" Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
数据上下文已设置并正常工作.我从MainViewModel填充了Shapes,并且矩形确实出现在了屏幕上,但是问题是我无法将矩形放置在Canvas
内的确切Left
和Top
位置,即它们只是放在(0,0).
The data context is set and working correctly. I populate the Shapes from MainViewModel and the rectangles do appear on the screen, but the problem is I can't get the rectangles to be placed at the exact Left
and Top
locations inside the Canvas
, i.e. they are just placed at (0,0).
我尝试绑定Path
的Canvas.Left
和Canvas.Top
(我尝试过的显而易见的方法),以及设置ItemContainerStyle
和Style
(我从WPF示例中找到的方法)应该做的一样.但是这些都不起作用(我已经在xaml中添加了这两种方法以供参考).
I tried both binding the Path
's Canvas.Left
and Canvas.Top
(the obvious method I tried) as well as setting an ItemContainerStyle
with a Style
(a method I found from a WPF example) that is supposed to do the same. But neither of these work (I've added both methods in the xaml for reference).
那么我在做错什么,如何使矩形出现在相应的位置?
So what am I doing wrong and how do I make the rectangles appear at the corresponding positions ?
我的问题与用于WPF的问题相同,但我的目标是Windows Metro/uwp,但无法接受该答案.
Edit : My question is the same as this one for WPF except that I'm targeting windows metro/uwp for which that accepted answer doesn't work.
通过绑定到Transform
来解决问题.
Got around the problem by binding into a Transform
instead.
<Path Data="{Binding PathData}" Stroke="White" StrokeThickness="3">
<Path.RenderTransform>
<CompositeTransform TranslateX="{Binding Left}" TranslateY="{Binding Top}"/>
</Path.RenderTransform>
</Path>