在Code Behind中按名称获取嵌套ListView

时间:2015-02-24 12:43:52

标签: c# wpf listview

我有以下嵌套的ListViews:

<!-- Display a list of each CustomTab -->
<!-- Drag & Drop functionality implemented in code behind using ListViewDragDropManager -->
<ListView Name="TasksListView"
          ItemsSource="{Binding Model.TaskCollection, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
          BorderThickness="0">

    <ListView.ItemTemplate>
        <DataTemplate>
            .....
            <!-- Parameters List -->
            <ListView Name="TaskParameterListView"
                      ItemsSource="{Binding TaskParameterCollection, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                      BorderThickness="0">

                <ListView.ItemTemplate>
                    <DataTemplate>
                        .....
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

        </DataTemplate>
    </ListView.ItemTemplate>            
</ListView>

我需要访问后面代码中的TaskParameterListView。我怎样才能获得对这个对象的引用?

使用TasksListView我只需拨打this.TasksListView

即可访问它

1 个答案:

答案 0 :(得分:0)

以下是使用FrameworkTemplate.FindName找到内部ListView的方法:

DependencyObject container = TasksListView
   .ItemContainerGenerator
   .ContainerFromItem(TasksListView.SelectedItem);

if (container != null)
{
   ContentPresenter presenter = GetPresenter(container);
   ListView listView = presenter
      .ContentTemplate
      .FindName("TaskParameterListView", presenter) as ListView;
}

在ListBoxItem中查找ContentPresenter的其他方法:

private static ContentPresenter GetPresenter(DependencyObject reference)
{
   for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); i++)
   {
      DependencyObject child = VisualTreeHelper.GetChild(reference, i);
      ContentPresenter presenter =
         child as ContentPresenter ??
         GetPresenter(child);

      if (presenter != null)
      { return presenter; }
   }

   return null;
}