查找控件的直接祖先/父级

Kev*_*n M 4 c# wpf user-controls casting parent-child

我有一个UserControl名字AddressTemplate,其中包含StackPanel各种各样的Labels&Textboxes.我需要的是一种方法来找到其中一个控件的直接祖先/父级AddressTemplate.从本质上讲,我需要一种方法来确定给定Textbox是否在其中AddressTemplate,或者在此之外UserControl,并且只是一个独立的控件.

到目前为止我想出的是:

private bool FindParent(Control target)
    {
        Control currentParent = new Control();

        if (currentParent.GetType() == typeof(Window))
        {

        }
        else if (currentParent.GetType() != typeof(AddressTemplate) && currentParent.GetType() != null)
        {
            currentParent = (Control)target.Parent;
        }
        else
        {
            return true;
        }

        return false;            
    }
Run Code Online (Sandbox Code Playgroud)

问题是,我不断收到InvalidCastException,因为它无法将StackPanel转换为Control.有人知道正确的演员阵容,还是一个可行的方法来解决这个问题?

Phi*_*eck 6

你可能想在LogicalTreeHelper.GetParent这里使用,它返回一个DependencyObject:

//- warning, coded in the SO editor window
private bool IsInAddressTemplate(DependencyObject target)
{
    DependencyObject current = target;
    Type targetType = typeof(AddressTemplate);

    while( current != null)
    {
       if( current.GetType() == targetType)
       {
          return true;
       }
       current = LogicalTreeHelper.GetParent(current);
    }
    return false;
 }
Run Code Online (Sandbox Code Playgroud)

这将走向逻辑父树,直到找不到父级或您正在寻找的用户控件.有关详细信息,请查看MSDN上的Wpf中的Trees