开发者

How do I get the X,Y position of a UserControl within a Canvas?

I have a simple UserControl implemented as below - which I place in a Canvas. I move it using Multi-touch and I want to be able to read its new X,Y postion using procedural C# code. Ideally I would like to have X and Y as two properties or as a Point (X,Y).

<UserControl x:Class="TouchControlLibrary.myControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-comp开发者_StackOverflow社区atibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="64" d:DesignWidth="104">
    <Border Name="ControlBorder" BorderThickness="1" BorderBrush="Black">
        <DockPanel Margin="1" Height="60 " Width="100">
            <StackPanel  DockPanel.Dock="Left" Background="Gray"  Width="20" >
                <Button Background="#FFDEDE53" Padding="0">In</Button>
            </StackPanel>
            <StackPanel  DockPanel.Dock="Right" Background="Gray"  Width="20" >
                <Button Background="#FFE8B48F" Padding="0">Out</Button>
            </StackPanel>
        </DockPanel>  
    </Border>
</UserControl>

I expected to be able to create an attached property for each of 'X' and 'Y' and fill them from Canvas.Left and Canvas.Top, using binding or some form of attached property or maybe something else entirely.

However, despite spending quite some time searching for a solution, everything I found so far seems to be 'not quite what is needed'.

What would you suggest I do to solve this problem?


let me see if I have this right, you create a new instance of the user control and add it to a canvas? Then you move it using Multi-touch (how do you do this? via a behaviour or manually?), and at any one time you want to read the new X/Y position of the instance of the user control relative to the Canvas?

Why cant you just read the same thing that is being changed when you move it via touch? Have you had a look at the RenderTransform property, this is what is usually changed when you manipulate something using a behavior or manual adjustments.


Well, here's a sample code i've for to get the Y, you can figure out the X hope this is what you need:

Point current = e.GetPosition(MyControl as UIElement); //where your control is
Point top = e.GetPosition(Canvas as UIElement); //or maybe just the height of the canvas
Thickness margin = new Thickness();
margin.Top = top.Y - current.Y; //distance from the top
MyControl.Margin = margin;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜