如何在Canvas

时间:2016-06-14 18:36:40

标签: xaml windows-store-apps winrt-xaml uwp mvvm-light

在Windows 8.1 Metro应用程序中,我正在尝试将视图模型中的一组形状绑定到MainPage.xaml中。每个形状都有一个LeftTop以及一个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填充Shapes并且矩形确实出现在屏幕上,但问题是我无法将矩形放置在{{1}内的确切LeftTop位置},即它们只是放在(0,0)。

我尝试绑定Canvas的{​​{1}}和Path(我尝试的显而易见的方法)以及设置Canvas.Left Canvas.Top (我从WPF示例中找到的方法)应该做同样的事情。但这些都不起作用(我在xaml中添加了两种方法以供参考)。

那么我做错了什么以及如何让矩形出现在相应的位置?

编辑:我的问题与 this one for WPF相同,只是我的目标是windows metro / uwp,但接受的答案无效。

1 个答案:

答案 0 :(得分:2)

通过绑定到Transform来解决问题。

<Path Data="{Binding PathData}" Stroke="White" StrokeThickness="3">
    <Path.RenderTransform>
         <CompositeTransform TranslateX="{Binding Left}" TranslateY="{Binding Top}"/>
    </Path.RenderTransform>
</Path>