如何在WP 8.1应用程序中获取xaml ListView的行数?

本文关键字:ListView xaml 获取 WP 应用程序 | 更新日期: 2023-09-27 18:14:15

为什么我的行号没有显示?如果我在WP SilverLight应用程序和ListBox中使用它,效果很好。但是对于ListView,它不会。

下面是我的代码:
 public object Convert(object value, Type targetType, object parameter, string language)
    {
        var dependencyObject = value as DependencyObject;
        var item = FindFirstParentOfType<ListView>(dependencyObject);
        if (item == null)
            return null;
        var listView = (ListView)ItemsControl.ItemsControlFromItemContainer(item);
        if (listView == null)
            return null;
        return listView.IndexFromContainer(item) + 1;
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
    private static T FindFirstParentOfType<T>(DependencyObject dependencyObject)
        where T : DependencyObject
    {
        while (true)
        {
            if (dependencyObject == null)
                return null;
            var parent = VisualTreeHelper.GetParent(dependencyObject);
            var findFirstParentOfType = (parent as T);
            if (findFirstParentOfType != null)
                return findFirstParentOfType;
            dependencyObject = parent;
        }
    }

在ListView的xaml页面我这样做:

 <ListView ItemsSource="{Binding ObjectsList}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent},
                                        Converter={StaticResource ListViewItemIndexConverter}, Mode=OneTime}"
                                               Foreground="White" 
                                               FontSize="40" />
                                    <TextBlock Text="{Binding Name}" />
                                </StackPanel>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

你知道我忘了什么或做错了什么吗?

如何在WP 8.1应用程序中获取xaml ListView的行数?

您的Convert方法是错误的。

当你寻找FindFirstParentOfType<ListView>时,它应该是FindFirstParentOfType<ListViewItem>

方法应该是这样的:

public object Convert(object value, Type targetType, object parameter, string language)
{
    var dependencyObject = value as DependencyObject;
    var item = FindFirstParentOfType<ListViewItem>(dependencyObject);
    if (item == null)
        return null;
    var listView = (ListView)ItemsControl.ItemsControlFromItemContainer(item);
    if (listView == null)
        return null;
    return listView.IndexFromContainer(item) + 1;
}