【问题标题】:C# WPF Want the child of the Stackpanel on clickC# WPF 希望 Stackpanel 的子项单击
【发布时间】:2016-08-07 18:27:14
【问题描述】:

我正在使用 StackPanel。在我的应用程序中,我必须显示一个包含 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 事件?
  • 不,你能不能给我一个提示如何处理这个事件? ;D
  • MouseDown 和 PreviewMouse down 事件的工作方式相同,但具有冒泡和隧道行为。您可以像使用 MouseDown 一样使用 PreviewMouseDown。

标签: c# .net wpf stackpanel


【解决方案1】:

您可以使用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();
    }
}

【讨论】:

    【解决方案2】:

    试试 eventargs 的 OriginalSource。 OriginalSource 给出了对哪个 MouseDown 的控制

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

    【讨论】:

    • 然后将image 传递到您的新窗口中。
    【解决方案3】:

    在你的 StackPanel 的 MouseDown 事件中,你可以试试;

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

    看看这是否有帮助。

    【讨论】:

      【解决方案4】:

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

      或者,get control under mouse cursor

      【讨论】:

      • Mhm .. 好的,但是我如何在运行时创建的图像上使用它?但我想这就是我正在寻找的:)
      • @user3793935 myImage.MouseDown += ClickHandler?
      【解决方案5】:

      虽然这有效。

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

      我仍然建议您使用 MVVM 并通过 CommandBinding 绑定命令。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 2021-11-04
        相关资源
        最近更新 更多