【问题标题】:xaml get selected view in ListViewxaml 获取 ListView 中的选定视图
【发布时间】:2014-03-03 08:53:29
【问题描述】:

我想在列表视图中获取选定的项目。但我想获得未绑定的项目,我想获得被选中的视图。所以就我而言:

 <ListView.ItemTemplate>
            <DataTemplate>
                <local:MyCustomUserControl BindedItem="{Binding}"/> 
            </DataTemplate>
        </ListView.ItemTemplate>

我想获取现在选择的 MyCustomUserControl 对象。谢谢,如果之前有人问过类似的问题,我们很抱歉。

【问题讨论】:

  • 这个答案对你有用吗?
  • 我会在几个小时后检查

标签: c# wpf xaml listview windows-store-apps


【解决方案1】:

您可以使用ItemContainerGenerator 获取底层容器,即ListViewItem,然后您可以通过遍历VisualTree 来获得控制权。

首先x:Name 提供给您的 ListView,以便您可以使用该名称从后面的代码中访问它:

<ListView x:Name="listView">
   ...
</ListView>

第二,从ItemContainerGenerator获取容器并遍历VisualTree获取你的子UserControl:

var listViewItem = listView.ItemContainerGenerator
                    .ContainerFromItem(listView.SelectedItem);
var customControl = FindChildControl<MyCustomUserControl>(listViewItem);

FindChildControl 是遍历 Visual Tree 的辅助方法:

    private T FindChildControl<T>(DependencyObject control)
                                   where T : DependencyObject
    {
        T foundChild = null;
        int childNumber = VisualTreeHelper.GetChildrenCount(control);
        for (int i = 0; i < childNumber; i++)
        {
            var child = VisualTreeHelper.GetChild(control, i);
            if (child != null && child is T)
                foundChild = (T)child;
            else
                foundChild = FindChildControl<T>(child);
        }
        return foundChild;
    }

注意:如果在 Windows 8.1 中使用 Windows 应用商店应用程序,ItemContainerGenerator will return null if you have not set an ItemsPanel。相反,直接在控件上使用相同的方法。在下面的示例中,listView.ItemContainerGenerator.ContainerFromItem 将改为 listView.ContainerFromItem

【讨论】:

  • ItemContainerGenerator 未找到。对不起,我忘了说:我正在编写 Windows 商店应用程序。
  • 我更新了答案以注意 Windows 8.1 中的更改。在大多数情况下,他们不赞成使用ItemContainerGenerator。请参阅注释以获取更多说明。
  • @Nate - 感谢更新,但我无法测试它,因为我没有 Windows 8.1 可供使用。
  • @Boris - 如果它现在适合您,您能否在最后验证它?
  • 对不起,这不起作用,FindChildControl 方法总是返回 null。
猜你喜欢
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多