Окно Windows Phone 8.1 со списком выбора дубликатов

1

Я создал простой проект, который отображает список с элементами, которые включают флажок. Когда пользователь выбирает флажок для нескольких элементов, некоторые флажки ниже (вне отображаемой области) также проверяются без участия пользователя. Этот "фантомный" выбор происходит для предметов прибл. 30-я позиция.

Я пытался:

  • удалить интерфейс INotifyPropertyChanged из класса
  • изменить ObservableCollection to List
  • изменить ListView на GridView

Без эффекта.

Code:

Class_Test_CheckBox.cs

using System;
using System.ComponentModel;

namespace App_Text_CheckBox
{
    public class Class_Test_CheckBox : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private Int64 _idPoint;
        private string _textContent;
        private bool _selected;
        private int _tag;

        public Int64 IdPoint
        {
            get { return _idPoint; }
            set
            {
                if (_idPoint != value)
                {
                    _idPoint = value;
                    RaisePropertyChanged("IdPoint");
                }
            }
        }

        public string TextContent
        {
            get { return _textContent; }
            set
            {
                if (_textContent != value)
                {
                    _textContent = value;
                    RaisePropertyChanged("TextContent");
                }
            }
        }

        public bool Selected
        {
            get { return _selected; }
            set
            {
                if (_selected != value)
                {
                    _selected = value;
                    RaisePropertyChanged("Selected");
                }
            }
        }

        public int Tag
        {
            get { return _tag; }
            set
            {
                if (_tag != value)
                {
                    _tag = value;
                    RaisePropertyChanged("Tag");
                }
            }
        }

        protected void RaisePropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}

Page_Test_CheckBox.xaml:

<Page
    x:Class="App_Text_CheckBox.Page_Test_CheckBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App_Text_CheckBox"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>
        <!--Collection of items displayed by this page-->
        <CollectionViewSource x:Name="itemsTestCheckBox"/>
    </Page.Resources>

    <Grid x:Name="LayoutRoot">

        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Title Panel -->
        <StackPanel Grid.Row="0" Margin="19,0,0,0">
            <TextBlock Text="TEST APPLICATION" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
            <TextBlock Text="Test CheckBox" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
        </StackPanel>

        <!--TODO: Content should be placed within the following grid-->
        <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
            <ListView
                ItemsSource="{Binding Source={StaticResource itemsTestCheckBox}}"
                ScrollViewer.HorizontalScrollMode="Disabled"
                ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                ScrollViewer.VerticalScrollMode="Auto"
                ScrollViewer.VerticalScrollBarVisibility="Auto" >
                <ListView.ItemTemplate >
                    <DataTemplate >
                        <Grid Margin="1">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="40"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Grid Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left">
                                <CheckBox x:Name="cb_Test_CheckBox" Tag="{Binding Tag}" IsChecked="{Binding Selected}" Checked="cb_Test_CheckBox_Checked" Unchecked="cb_Test_CheckBox_Unchecked"  />
                            </Grid>
                            <TextBlock Grid.Column="1" Tag="{Binding Tag}" Text="{Binding TextContent}" TextWrapping="NoWrap" FontSize="16" VerticalAlignment="Center"/>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </Grid>
</Page>

Page_Test_CheckBox.xaml.cs:

using App_Text_CheckBox.Common;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace App_Text_CheckBox
{
     public sealed partial class Page_Test_CheckBox : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        // Test ObservableCollection
        public ObservableCollection<Class_Test_CheckBox> ObservableCollection_Test_CheckBox = new ObservableCollection<Class_Test_CheckBox>();

        public Page_Test_CheckBox()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
        }

        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }

        #region NavigationHelper registration

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);

            // Create 55 items
            for (int ii = 0; ii < 55; ii++)
            {
                Class_Test_CheckBox newItem = new Class_Test_CheckBox();
                newItem.IdPoint = (long)ii;
                newItem.Selected = false;       //for Binding CheckBox
                newItem.Tag = ii;
                newItem.TextContent = (ii + 1).ToString() + ". row - Lorem Ipsum Dolor ...";
                ObservableCollection_Test_CheckBox.Add(newItem);
            }
            //items -> source
            itemsTestCheckBox.Source = ObservableCollection_Test_CheckBox;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        private void cb_Test_CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            int index = (int)((sender as CheckBox).Tag);
            ObservableCollection_Test_CheckBox[index].Selected = true;
            ObservableCollection_Test_CheckBox[index].TextContent = (index + 1).ToString() + ". row - LOREM IPSUM DOLOR " + index.ToString() + " " + ObservableCollection_Test_CheckBox[index].Selected.ToString();
        }

        private void cb_Test_CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            int index = (int)((sender as CheckBox).Tag);
            ObservableCollection_Test_CheckBox[index].Selected = false;
            ObservableCollection_Test_CheckBox[index].TextContent = (index + 1).ToString() + ". row - lorem ipsum dolor " + index.ToString() + " " + ObservableCollection_Test_CheckBox[index].Selected.ToString();

        }
    }
}

Есть ли ошибка или как избежать дублирования выбора?

Теги:
checkbox
listbox

1 ответ

0

Я также столкнулся с этой проблемой. Эта проблема, по-видимому, является результатом активации виртуализации. Существует обходной путь, но я все еще считаю это ошибкой.

Здесь ссылка на этот вопрос:

Ещё вопросы

Сообщество Overcoder
Наверх
Меню