如何在Canvas中绑定形状/控件的绝对坐标 [英] How to bind absolute coordinates of a shape/control inside Canvas

查看:128
本文介绍了如何在Canvas中绑定形状/控件的绝对坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows 8.1 Metro应用程序上,我尝试将视图模型中的形状集合绑定到MainPage.xaml中.每个形状将具有一个LeftTop和一个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内的确切LeftTop位置,即它们只是放在(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).

我尝试绑定PathCanvas.LeftCanvas.Top(我尝试过的显而易见的方法),以及设置ItemContainerStyleStyle(我从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>

这篇关于如何在Canvas中绑定形状/控件的绝对坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆