2010-03-16 6 views
3

В следующем WPF приложение, у меня есть Изображение в ContentControl. Когда пользователь нажимает на изображение , как я могу получить x/y координаты где mouse нажали на изображение?Как получить координаты щелчка мыши мыши в обработчике событий?

XAML:

<Window x:Class="TestClick828374.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
    <StackPanel Margin="10"> 
     <ContentControl Content="{Binding TheImage}" MouseDown="ContentControl_MouseDown"/> 
    </StackPanel> 
</Window> 

Code-Behind:

using System; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.ComponentModel; 

namespace TestClick828374 
{ 
    public partial class Window1 : Window, INotifyPropertyChanged 
    { 
     #region ViewModelProperty: TheImage 
     private Image _theImage; 
     public Image TheImage 
     { 
      get 
      { 
       return _theImage; 
      } 

      set 
      { 
       _theImage = value; 
       OnPropertyChanged("TheImage"); 
      } 
     } 
     #endregion 

     public Window1() 
     { 
      InitializeComponent(); 
      DataContext = this; 

      TheImage = new Image(); 
      TheImage.Source = new BitmapImage(new Uri(@"c:\test\rectangle.png")); 
      TheImage.Stretch = Stretch.None; 
      TheImage.HorizontalAlignment = HorizontalAlignment.Left; 

     } 

     #region INotifiedProperty Block 
     public event PropertyChangedEventHandler PropertyChanged; 

     protected void OnPropertyChanged(string propertyName) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 

      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
     #endregion 

     private void ContentControl_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) 
     { 
      //how to get the coordinates of the mouse click here on the image? 
     } 

    } 
} 

ответ

9

Нашел:

Point clickPoint = e.GetPosition(TheImage); 

Вот мой полный пример кода, показывающий решение:

http://www.tanguay.info/web/index.php?pg=codeExamples&id=364

+1

Ваша ссылка мертва. –

+0

Альтернативно, вы можете использовать внутренний метод Mouse.GetPosition (TheImage), который не имеет MouseEventsArgs или MouseButtonEventArgs – EpiGen