4

I am using StackPanels. In my application I have to show a multi tiff with 3 to x images and have to open them in a new window after I click on one of them.

Showing them is easy:

public void Bilder_anzeigen(string path)
{
    TiffBitmapDecoder decoder = new TiffBitmapDecoder(new Uri(path), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

    foreach (var i in decoder.Frames)
    {
        Image myImage = new Image();
        myImage.Source = i;
        Stackpanel_Tiff.Children.Add(myImage);
    }
}

But how can I get a child with a click on the StackPanel? There is a MouseDown Event, but after it is raised, I don't know on which image i clicked. I just know there was a click. How can I find the image that was clicked?

Athari
  • 33,702
  • 16
  • 105
  • 146
user3793935
  • 411
  • 5
  • 22

5 Answers5

6

You can find out which Image was clicked on very easily using the PreviewMouseDown event and the OriginalSource of the MouoseButtonEventArgs object:

<StackPanel PreviewMouseDown="StackPanel_PreviewMouseDown">
    <Image Source="Images/Add_16.png" Stretch="None" />
    <Image Source="Images/Edit_16.png" Stretch="None" />
    <Image Source="Images/Copy_16.png" Stretch="None" />
</StackPanel>

...

private void StackPanel_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.OriginalSource is Image)
    {
        string imageSource = ((Image)e.OriginalSource).Source.ToString();
    }
}
Sheridan
  • 68,826
  • 24
  • 143
  • 183
3

Try OriginalSource of eventargs. OriginalSource give the control on which MouseDown

       private void Sp_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        var image=e.OriginalSource as Image;
    }
yo chauhan
  • 12,079
  • 4
  • 39
  • 58
3

In your StackPanel's MouseDown Event, you can try;

if (e.OriginalSource is Image)
{
    var tapImage = (Image)e.OriginalSource;
    //tapImage is the Image on which user tapped.
}

see if this helps.

Vyas
  • 2,734
  • 18
  • 14
2

You can just use Image.MouseDown or Image.MouseUp event.

Alternatively, get control under mouse cursor.

Community
  • 1
  • 1
Athari
  • 33,702
  • 16
  • 105
  • 146
0

while this works.

 image.MouseDown += (e, v) => { //enter your code };

I would still recommend you to use MVVM and bind the command through CommandBinding.

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Hiệp Lê
  • 636
  • 4
  • 8