WPF:为什么我的DataTemplate项找不到它的父项?

时间:2011-03-18 19:13:05

标签: wpf listview datatemplate

我的* .xaml中有一个DataTemplate,它是我的listview控件的datatemplate:

<DataTemplate x:Key="listViewSourceItemTemplate" DataType="{x:Type this:SourceItemField}">
    <this:SourceItemField Background="LightPink">
    <i:Interaction.Behaviors>
        <ei:MouseDragElementBehavior/>
    </i:Interaction.Behaviors>
    <StackPanel Orientation="Horizontal" Margin="5,10,5,10" Background="LightGray">
        <TextBlock Text="{Binding Path=FieldType,StringFormat=\{0\}}" Margin="0,0,5,0" />
        <TextBlock Text="{Binding Path=ContextName,StringFormat=\{0\}}" Margin="0,0,5,0" />
        <TextBlock Text="{Binding Path=FieldName,StringFormat=\{0\}}" Margin="0,0,5,0" />
        <TextBlock Text="{Binding Path=ConnectionNumber,StringFormat=\{0\}}" Margin="0,0,5,0" />
    </StackPanel>
</this:SourceItemField>

在我的C#代码中,我有以下程序:

    public void SetPosition()
    {
        Center = this.TransformToAncestor(FindAncestor<Canvas>(this)).Transform(new Point(this.ActualWidth / 2, this.ActualHeight / 2));
    }


    // walk up the visual tree for parent of type T
    private static T FindAncestor<T>(DependencyObject current)
        where T : DependencyObject
    {
        do
        {
            if (current is T)
            {
                return (T)current;
            }
            current = VisualTreeHelper.GetParent(current);
        }
        while (current != null);
        return null;
    }

“this”是SourceItemField,为什么VisualTreeHelper.GetParent()将其祖先返回为“null”?为什么这个SourceItemField的父级不是我的列表视图?

1 个答案:

答案 0 :(得分:0)

您确定要查找Canvas而不是ListView作为祖先吗?

即代替:

  

public void SetPosition()
{
      Center = this.TransformToAncestor(FindAncestor&lt; Canvas &gt;(this))。变换(new   点(this.ActualWidth / 2,   this.ActualHeight / 2));
}

这个:

public void SetPosition() 
{ 
    Center = this.TransformToAncestor(FindAncestor<ListView>(this)).Transform(new Point(this.ActualWidth / 2, this.ActualHeight / 2)); 
}