在ListView UWP中显示行号

时间:2020-11-03 15:51:08

标签: c++ listview uwp

我正在寻找一种解决方案,以显示ListView中每个元素的行号。此外,在从列表中删除某些元素之后或将元素移到其他位置时,需要更新行号。我正在使用UWP(C ++)。

1 个答案:

答案 0 :(得分:1)

如果要在ListView中显示行号,建议您使用数据绑定。您可以参考文档XAML controls; bind to a C++/WinRT propertyXAML items controls; bind to a C++/WinRT collection,以获取有关数据绑定的详细代码。

以上述文档中实现的项目Bookstore为例,我们需要使用DataTemplate来更改ListView中每个项目的内容,并更新每个项目的索引通过添加IObservableVector事件更改ListView实例(它是IObservableVector<T>.VectorChanged的数据绑定源)时的项目。

例如:

  1. 添加一个表示ListView中每个项目的索引的属性。

BookSku.idl

    runtimeclass BookSku : Windows.UI.Xaml.Data.INotifyPropertyChanged
    {
        ……
        Int16 Index;
    }

BookSku.h

struct BookSku : BookSkuT<BookSku>
{
    ……
    int16_t Index();
    void Index(int16_t value);

private:
    ……
    int16_t m_index = 0;
};

BookSku.cpp

int16_t BookSku::Index()
{
    return m_index;
}
void BookSku::Index(int16_t value)
{
    if (m_index != value)
    {
        m_index = value;
        m_propertyChanged(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs{ L"Index" });
    }
}
  1. 启动Index时启动m_bookSkus属性,并为m_bookSkus添加VectorChanged事件,以在m_bookSkus的项目更改时更新索引。

BookstoreViewModel.cpp

    BookstoreViewModel::BookstoreViewModel()
    {
        m_bookSkus = winrt::single_threaded_observable_vector<Bookstore::BookSku>();
        m_bookSkus.VectorChanged([](IObservableVector<Bookstore::BookSku> const& sender, IVectorChangedEventArgs const& args) {

        for (int16_t i = 0; i < sender.Size(); i++)
        {
             auto item = sender.GetAt(i);
             item.Index(i+1);
        }

        });

    int16_t index=0;
    
    m_bookSku = winrt::make<Bookstore::implementation::BookSku>(L"Title1");
    index = m_bookSkus.Size() + 1;
    m_bookSku.Index(index);

    m_bookSkus.Append(m_bookSku);

    m_bookSku = winrt::make<Bookstore::implementation::BookSku>(L"Title2");
    index = m_bookSkus.Size() + 1;
    m_bookSku.Index(index);

    m_bookSkus.Append(m_bookSku);

    m_bookSku = winrt::make<Bookstore::implementation::BookSku>(L"Title3");
    index = m_bookSkus.Size() + 1;
    m_bookSku.Index(index);

    m_bookSkus.Append(m_bookSku);
}
  1. 通过在XAML中使用ListViewDataTemplate的每个项目中显示索引。

MainPage.xaml

    <ListView ItemsSource="{x:Bind MainViewModel.BookSkus}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:BookSku">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{x:Bind Index,Mode=OneWay}" Margin="0,0,10,0"/>
                    <TextBlock Text="{x:Bind Title, Mode=OneWay}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

有关DataTemplate的更多信息,请参考document,有关在C ++ / WinRT中使用委托处理事件的信息,请参考document

相关问题