2016-11-27 51 views
0

實例我有ListView控件與用戶控件在它的DataTemplate對象的父:獲得通過的DataTemplate

<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爲空, parent2爲ListViewItemPresenter, parent3也爲null, parent4是我的ViewModel類(其中MyCollection所在的位置)。

如何獲得實際的ListView?

回答

0

嘗試這些VisualTreeExtensionsUWPCommunityToolkit

對於從ListView.ItemTemplateDataTemplate)獲取父ListView使用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>(); 
    }