Home > OS >  How to get the coordinates of a WPF PresentationFramework object?
How to get the coordinates of a WPF PresentationFramework object?

Time:03-10

In my XAML, I have something like:

<client:View ...
    ...
    <controls:Location Canvas.Left="169500"
                       Canvas.Top="52610"
                       LocationName="Location_Name"
                       Rotation="0" MouseDoubleClick="Location_MouseDoubleClick"/>

A Location is a subclass from , as you can see:

using System.Windows.Controls;
...
public class Location : UserControl ...

In the corresponding *.xaml.cs, I have:

    private void Location_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        <namespace>.Location Loc = sender as <namespace>.Location;

        Point location_Point = Mouse.GetPosition(this);
        // This gives the X and Y coordinates of the mouse pointer.
        // I would like to know the X and Y coordinates of the Location object,
        // without needing to pass via a mouse event, such as:
        Loc. // but what attributes/properties contain that information?

Does anybody have an idea?
Thanks in advance

CodePudding user response:

You are most likly looking for a way how to read an attached property.

Reading an attached property (or any dependency property) can be with the GetValue method of a DependendyObject.

//first cast your sender to a DependencyObject
if (sender is DependencyObject dpObj)
{
    //GetValue will return an object
    //Canvas has a static member for the attached property LeftProperty
    var value = dpObj.GetValue(Canvas.LeftProperty);
    
    //cast value to double
    if (value is double canvasLeft)
    {
        //do something with canvasLeft
    }
    else
    {
        //do something if the value isn't a double, should never be the case
    }
}
else
{
    //do something if sender isn't a DependencyObject
}

or without all those safe casts

var canvasLeft = (double)((DependencyObject)sender).GetValue(Canvas.LeftProperty);

GetValue docs:

https://docs.microsoft.com/en-us/dotnet/api/system.windows.dependencyobject.getvalue

Notice:

Code uses latest c# language syntax.

  • Related