Einzelnen Beitrag anzeigen

aMuTeX

Registriert seit: 8. Mai 2003
Ort: Luzern
54 Beiträge
 
Delphi 10.2 Tokyo Professional
 
#2

AW: [WPF] "Auflösung" von Controls in ItemsControl

  Alt 25. Okt 2016, 10:50
Hallo

Warum das so ist habe ich auch nie verstanden. "e.Source" und "e.OriginalSource" sind nicht gleich, obwohl der VisualTree sonst eigentlich gleich ist.

Das gewünschte Ergebnis kann aber so erreicht werden:
Code:
private void TestCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Title = UIHelper.FindVisualParent<TestControl>(e.OriginalSource as DependencyObject).GetType().Name;
}
Code:
public static class UIHelper
{
    /// <summary>
    /// Finds a parent of a given item on the visual tree.
    /// </summary>
    /// <typeparam name="T">The type of the queried item.</typeparam>
    /// <param name="child">A direct or indirect child of the queried item.</param>
    /// <returns>The first parent item that matches the submitted type parameter.
    /// If not matching item can be found, a null reference is being returned.</returns>
    public static T FindVisualParent<T>(DependencyObject child)
      where T : DependencyObject
    {
        // get parent item
        DependencyObject parentObject = VisualTreeHelper.GetParent(child);


        // we’ve reached the end of the tree
        if (parentObject == null) return null;

        // check if the parent matches the type we’re looking for
        T parent = parentObject as T;
        if (parent != null)
        {
            return parent;
        }
        else
        {
            // use recursion to proceed with next level
            return FindVisualParent<T>(parentObject);
        }
    }
}
Hoffe das hilft.
Gruss
Stefan
  Mit Zitat antworten Zitat