簡體   English   中英

C#WPF想要點擊Stackpanel的孩子

[英]C# WPF Want the child of the Stackpanel on click

我正在使用StackPanels。 在我的應用程序中,我必須顯示具有3到x圖像的多重tiff,並且在我點擊其中一個之后必須在新窗口中打開它們。

顯示它們很簡單:

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);
    }
}

但是如何讓孩子點擊StackPanel? 有一個MouseDown事件,但在它被引發后,我不知道我點擊了哪個圖像。 我只知道有一個點擊。 如何找到點擊的圖像?

您可以使用PreviewMouseDown事件和MouoseButtonEventArgs對象的OriginalSource非常輕松地找到單擊的Image

<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();
    }
}

嘗試使用eventargs的OriginalSource。 OriginalSource給出了MouseDown的控件

       private void Sp_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        var image=e.OriginalSource as Image;
    }

在StackPanel的MouseDown事件中,您可以嘗試;

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

看看這是否有幫助。

您可以使用Image.MouseDownImage.MouseUp事件。

或者, 在鼠標光標下獲得控制權

這雖然有效。

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

我仍然建議您使用MVVM並通過CommandBinding綁定命令。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM