获取DataTemplate实例化的对象的父级

时间:2016-11-27 07:48:29

标签: c# listview uwp-xaml

我在其DataTemplate中使用带有UserControl的ListView:

<ListView ItemSource="{Binding MyCollection}" x:Name="MyListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <MyUserControl Loaded="OnLoaded" Content="{Binding MyProperty}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

当我尝试在MyUserControl的代码中获取父ListView时(以不同的方式):

private void OnLoaded(object sender, RoutedEventArgs e)
{
    var parent1 = Parent;
    var parent2 = VisualTreeHelper.GetParent(this);
    var parent3 = FindName("MyListView");
    var parent4 = DataContext;
}

parent1为null, parent2是ListViewItemPresenter, parent3也是null, parent4是我的ViewModel类(MyCollection所在的位置)。

如何获得实际的ListView?

1 个答案:

答案 0 :(得分:0)

UWPCommunityToolkit

尝试这些VisualTreeExtensions

ListViewListView.ItemTemplate)获取父DataTemplate}使用FindVisualAscendant方法

    /// <summary>
    /// Find first ascendant control of a specified type.
    /// </summary>
    /// <typeparam name="T">Type to search for.</typeparam>
    /// <param name="element">Child element.</param>
    /// <returns>Ascendant control or null if not found.</returns>
    public static T FindAscendant<T>(this FrameworkElement element)
        where T : FrameworkElement
    {
        if (element.Parent == null)
        {
            return null;
        }

        if (element.Parent is T)
        {
            return element.Parent as T;
        }

        return (element.Parent as FrameworkElement).FindAscendant<T>();
    }

    /// <summary>
    /// Find first visual ascendant control of a specified type.
    /// </summary>
    /// <typeparam name="T">Type to search for.</typeparam>
    /// <param name="element">Child element.</param>
    /// <returns>Ascendant control or null if not found.</returns>
    public static T FindVisualAscendant<T>(this FrameworkElement element)
        where T : FrameworkElement
    {
        var parent = VisualTreeHelper.GetParent(element);

        if (parent == null)
        {
            return null;
        }

        if (parent is T)
        {
            return parent as T;
        }

        return (parent as FrameworkElement).FindVisualAscendant<T>();
    }