XAML c#-当UWP ListView具有DataTemplate时,在快速滚动时显示不正确的项

gywdnpxw  于 2022-12-07  发布在  C#
关注(0)|答案(1)|浏览(141)

我有一个ListView,它的目的是显示数据库中的每一个产品,它的工作的大部分,但当我向下滚动拖动滚动条,底部的项目最终是不正确的。
XAML定义:

<ListView x:Name="lst_Products" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="16,124,16,16" Width="300" ContainerContentChanging="lst_Products_ContainerContentChanging" Loaded="lst_Products_Loaded" BorderBrush="Black" BorderThickness="2" CornerRadius="16">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding Value}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

数据模板是存在的,所以我可以很容易地用SelectedValue获取产品ID号。根据MSDN论坛上一些受信任的社区成员(或者他们称之为突出海报的任何东西)的说法,这是当ItemsSourceObservableCollection<KeyValuePair<int,RelativePanel>>且具有可选值成员时正确显示ListView的唯一方法。
相关的C#代码:
第一个
对SQL处理程序的调用只是运行一个SQL查询并返回一个结果列表。如果您需要,我可以发布代码,但我可以向您保证没有进行排序。
A screenshot of what the list looks like. The bottom item should be "Coffee" - Button Test Product 2 is the second item in the list.
A screenshot of the SQL datatable with the "Coffee" product at the bottom where it should be.
在这种情况下,它只是底部的条目不正确,但其他时候它会在底部附近混乱5或6个条目。这似乎只发生在DataTemplate/ContentPresenter中,但如果没有它,RelativePanel就不会在列表中正确显示。最终,列表将显示有关产品的更多信息,据我所知,如果不将SQL数据转换为C#端的RelativePanel,就没有好的方法来实现这一点。
我很乐意接受关于解决模板混乱问题的建议,或者调整xaml,这样我就不需要模板来显示大量sql数据,而不需要模板,但是我很困惑。

vvppvyoh

vvppvyoh1#

c# -当UWP ListView具有DataTemplate时,在快速滚动时显示不正确的项
这个问题应该是由listview virtualization引起的,有两种方法可以解决这个问题,一种是通过将ItemsPanel设置为StackPanel来禁用listview虚拟化,如下所示

<ListView>
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

另一种方法是为你的模型类实现INotifyCollectionChanged接口。
使用RelativePanel集合作为数据源不是一个好的做法,更好的方法是在DataTemplate中创建RelativePanel,并与mode类属性绑定。
比如说

<ListView.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Index}" />
            <TextBlock Text="{Binding IsItem}" />
            <Image Source="{Binding ImageSource}" Visibility="Collapsed" />
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>

相关问题