Как я могу получить позиции startX и startY? - PullRequest
3 голосов
/ 30 декабря 2010

Как я могу получить позиции startX и startY rectToGetXAndY. Эта функциональность очень важна для моего приложения, но сводит меня с ума. Единственный подход, который приходит мне в голову, - попросить пользователя вручную нажать на верхнюю левую границу сетки и затем обработать событие mouseleftbuttondown. Очевидно, это не то решение, которое я хочу. Вот мой код: -

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="DelSilverlightApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="600" d:DesignWidth="800">

    <Grid x:Name="LayoutRoot" Background="DarkSlateGray">
        <Grid x:Name="rectToGetXAndY" Background="HotPink" Width="300" Height="300" HorizontalAlignment="Center" VerticalAlignment="Center">

        </Grid>
    </Grid>
</UserControl>

РЕДАКТИРОВАТЬ: -

Это код позади: -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DelSilverlightApp
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            GeneralTransform gt = rectToGetXAndY.TransformToVisual(null);
            Point p = gt.Transform(new Point(0, 0));
            MessageBox.Show(p.X + " " + p.Y);
        }
    }
}

Заранее спасибо:)

Ответы [ 3 ]

3 голосов
/ 30 декабря 2010

Я заставил его работать, используя код @AnthonyWJones, используя следующее:

XAML

        <UserControl x:Class="GetPositionUi.MainPage"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            mc:Ignorable="d"
            DataContext="{Binding RelativeSource={RelativeSource Self}}"
            d:DesignHeight="300" d:DesignWidth="400">

            <Grid x:Name="LayoutRoot" Background="DarkSlateGray">
                <Grid x:Name="rectToGetXAndY" 
                        Background="HotPink" 
                        Width="300" 
                        Height="300" 
                        HorizontalAlignment="Center" 
                        VerticalAlignment="Center">
                    <TextBlock x:Name="PositionTextBlock" Text="{Binding Path=ReferencePosition}"/>
                </Grid>
            </Grid>
        </UserControl>

Код:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;

    namespace GetPositionUi
    {
        public partial class MainPage : UserControl
        {

            #region ReferencePosition

            /// <summary>
            /// ReferencePosition Dependency Property
            /// </summary>
            public static readonly DependencyProperty ReferencePositionProperty =
                DependencyProperty.Register("ReferencePosition", typeof(Point), typeof(MainPage),
                    new PropertyMetadata((Point)(new Point(0, 0)),
                        new PropertyChangedCallback(OnReferencePositionChanged)));

            /// <summary>
            /// Gets or sets the ReferencePosition property.  This dependency property 
            /// indicates the reference position of the child element.
            /// </summary>
            public Point ReferencePosition
            {
                get { return (Point)GetValue(ReferencePositionProperty); }
                set { SetValue(ReferencePositionProperty, value); }
            }

            /// <summary>
            /// Handles changes to the ReferencePosition property.
            /// </summary>
            private static void OnReferencePositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                ((MainPage)d).OnReferencePositionChanged(e);
            }

            /// <summary>
            /// Provides derived classes an opportunity to handle changes to the ReferencePosition property.
            /// </summary>
            protected virtual void OnReferencePositionChanged(DependencyPropertyChangedEventArgs e)
            {
            }

            #endregion

            public MainPage()
            {
                InitializeComponent();
            }

            protected override Size ArrangeOverride(Size finalSize)
            {
                var arrangedSize = base.ArrangeOverride(finalSize);
                GeneralTransform gt = rectToGetXAndY.TransformToVisual(LayoutRoot);
                Point p = gt.Transform(new Point(0, 0));
                ReferencePosition = p;
                return arrangedSize;
            }
        }
    }

Ключевым моментом здесь является то, что сначала база позволяет расположить элементы управления, а затем использовать преобразование, чтобы найти позицию и, наконец, вернуть новый размерранж.

Я бы не рекомендовал показывать окно сообщения на этом этапе, но вы можете использовать измененный обратный вызов свойства зависимостей, чтобы делать все, что вы хотите с обновленной позицией.

2 голосов
/ 30 декабря 2010

В Silveright вы можете использовать этот код для определения текущей позиции X и Y rectToGetXAndY относительно LayoutRoot: -

GeneralTransform gt = rectToGetXAndY.TransformToVisual(LayoutRoot);
Point p = gt.Transform(new Point(0, 0));
0 голосов
/ 30 декабря 2010

Вы можете использовать VisualTreeHelper ...

Vector vector = VisualTreeHelper.GetOffset(rectToGetXAndY);
Point currentPoint = new Point(vector.X, vector.Y);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...