在Windows8.1Metro应用程序上,我尝试将视图模型中的一组形状绑定到MainPage.xaml中。每个形状都有一个Left
、Top
和一个PathData
,它将是一个RectangleGeometry
,其中包含我希望在相应位置在画布中绘制的矩形。
这是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的形状,并且矩形确实出现在屏幕上,但问题是我无法将矩形放置在Canvas
内的确切Left
和Top
位置,即它们只是放置在(0,0)。
我尝试了绑定Path
的Canvas.Left
和Canvas.Top
(这是我尝试过的明显的方法),也尝试用一个Style
(我从WPF示例中找到的方法)来设置ItemContainerStyle
,这两种工作都不是这样的(我在xaml中添加了这两个方法供参考)。
那么,我做错了什么,如何使矩形出现在相应的位置?
编辑:我的问题和 this one for WPF是一样的,只是我的目标是windows metro/uwp,而这个被接受的答案不起作用。
发布于 2016-06-14 12:18:06
通过绑定到Transform
来解决这个问题。
<Path Data="{Binding PathData}" Stroke="White" StrokeThickness="3">
<Path.RenderTransform>
<CompositeTransform TranslateX="{Binding Left}" TranslateY="{Binding Top}"/>
</Path.RenderTransform>
</Path>
https://stackoverflow.com/questions/37819679
复制相似问题