ListView Virtualization value repeating in Recycli

2019-05-09 13:12发布

问题:

I have a strange problem with virtualization enabled ListView control. I created a very small pilot app to reproduce the issue. When I type-in something for a few textboxes in the listview and then scrolling down, after a few pages the typed-in values are repeating in the untouched textboxes below.

Here is the XAML of the window:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Grid Name="mainGrid">
        <ListView ItemsSource="{Binding Path=DemoList}" >

            <VirtualizingStackPanel.IsVirtualizing>
                True
            </VirtualizingStackPanel.IsVirtualizing>
            <VirtualizingStackPanel.VirtualizationMode>
                Recycling
            </VirtualizingStackPanel.VirtualizationMode>

            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBox  MinHeight="20" MinWidth="200" Margin="4"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>

    </Grid>
</Window>

And the code-behind:

namespace WpfApplication3
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            demolist a = new demolist();
            mainGrid.DataContext = a;
        }
    }

    public class demolist
    {
        public demolist()
        {
            DemoList = new List<string>();

            for (int i = 0; i <= 5000; i++)
            {
                DemoList.Add("sss");
            }
        }
        public List<string> DemoList { get; set; }
    }
}

And a screen capture about the issue: http://kepfeltoltes.hu/120228/Capture1_www.kepfeltoltes.hu_.png

Is there any option to solve this issue? I guess it is related to the recycling mode, but I think this should not be the normal behaviour.

Thanks in advance,

István

回答1:

That's certainly an odd effect, but it's seems to be due to the recycling mode plus the fact you're not binding the TextBox.Text property to anything.

Change your code like this (sorry for change of names) and all should be well:

public class RecyclingListViewModel
{
    public RecyclingListViewModel()
    {
        Items = new List<DataItem>();

        for (int i = 0; i <= 5000; i++)
        {
            Items.Add(new DataItem{Id = i, Name = i.ToString(CultureInfo.InvariantCulture)});
        }
    }

    public List<DataItem> Items { get; set; }
}

public class DataItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}

<ListView ItemsSource="{Binding Path=Items}" >
<TextBox  MinHeight="20" MinWidth="200" Margin="4" Text="{Binding Name}"/>