如何在WP 8.1 App中获得xaml ListView的rownumbers?

时间:2015-09-23 13:24:10

标签: c# xaml listview windows-phone-8.1

为什么我的行号会出现?如果我在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>

知道我忘记了什么或做错了什么?

1 个答案:

答案 0 :(得分:1)

您的转换方法错误。

在您寻找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;
}