word-steps /toolkit/Microsoft.Phone.Controls.Toolkit/LongListSelector/LongListSelector.cs

Language C# Lines 2415
MD5 Hash 8928bc12903efcc29a2ab8c91de405eb Estimated Cost $48,097 (why?)
Repository https://bitbucket.org/jeremejevs/word-steps.git View Raw File View Project SPDX
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace Microsoft.Phone.Controls
{
    /// <summary>
    /// A virtualizing list designed for grouped lists. Can also be used with flat lists.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling"), TemplatePart(Name = ItemsPanelName, Type = typeof(Panel))]
    [TemplatePart(Name = PanningTransformName, Type = typeof(TranslateTransform))]
    [TemplatePart(Name = VerticalScrollBarName, Type = typeof(ScrollBar))]
    public partial class LongListSelector : Control
    {
        // The names of the template parts
        private const string ItemsPanelName = "ItemsPanel";
        private const string PanningTransformName = "PanningTransform";
        private const string VerticalScrollBarName = "VerticalScrollBar";

        private Panel _itemsPanel;
        private TranslateTransform _panningTransform;
        private ScrollBar _verticalScrollbar;
        private Popup _groupSelectorPopup;

        private Storyboard _panelStoryboard;
        private DoubleAnimation _panelAnimation;
        private DateTime _gestureStart;

        // Timer that controls how long it takes before a flick will be stopped on a touch down
        private DispatcherTimer _stopTimer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(50) };
        private bool _ignoreNextTap;
        private bool _firstDragDuringFlick;
        private double _lastFlickVelocity;

        // Duration used for animations while panning, instead of matching finger position exactly
        private static readonly Duration _panDuration = new Duration(TimeSpan.FromMilliseconds(100));
        private readonly IEasingFunction _panEase = new ExponentialEase();

        // Time that dragging will wait before deciding that a flick is not happening
        private static readonly TimeSpan _flickStopWaitTime = TimeSpan.FromMilliseconds(20);

        private int _scrollingTowards = -1;

        private const double BufferSizeDefault = 1.0;
        private double _bufferSizeCache = BufferSizeDefault;
        private double _minimumPanelScroll = float.MinValue;
        private double _maximumPanelScroll = 0;

        private bool _isLoaded;

        private bool _isPanning;
        private bool _isFlicking;
        private bool _isStretching;

        private double _dragTarget;
        private bool _isAnimating;

        private Size _availableSize;

        private Stack<ContentPresenter> _recycledGroupHeaders = new Stack<ContentPresenter>();
        private Stack<ContentPresenter> _recycledGroupFooters = new Stack<ContentPresenter>();
        private Stack<ContentPresenter> _recycledItems = new Stack<ContentPresenter>();
        private ContentPresenter _recycledListHeader = null;
        private ContentPresenter _recycledListFooter = null;

        private List<ItemTuple> _flattenedItems;
        private object _firstGroup;

        private INotifyCollectionChanged _rootCollection;
        private List<INotifyCollectionChanged> _groupCollections;

        private int _resolvedFirstIndex;
        private int _resolvedCount;
        private int _screenFirstIndex;
        private int _screenCount;

        private bool _balanceNeededForSizeChanged;

        #region ItemsSource DependencyProperty

        /// <summary>
        /// The DataSource property. Where all of the items come from.
        /// </summary>
        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        /// <summary>
        /// The DataSource DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(LongListSelector), new PropertyMetadata(null, OnItemsSourceChanged));

        private static void OnItemsSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            ((LongListSelector)obj).OnItemsSourceChanged();
        }

        private void OnItemsSourceChanged()
        {
            _flattenedItems = null;
            if (_isLoaded)
            {
                EnsureData();
            }
        }

        #endregion

        #region ListHeader DependencyProperty

        /// <summary>
        /// The ListHeader property. Will be used as the first scrollItem in the list.
        /// </summary>
        public object ListHeader
        {
            get { return (object)GetValue(ListHeaderProperty); }
            set { SetValue(ListHeaderProperty, value); }
        }

        /// <summary>
        /// The ListHeader DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ListHeaderProperty =
            DependencyProperty.Register("ListHeader", typeof(object), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region ListHeaderTemplate DependencyProperty

        /// <summary>
        /// The ListHeaderTemplate provides the template for the ListHeader.
        /// </summary>
        public DataTemplate ListHeaderTemplate
        {
            get { return (DataTemplate)GetValue(ListHeaderTemplateProperty); }
            set { SetValue(ListHeaderTemplateProperty, value); }
        }

        /// <summary>
        /// The ListHeaderTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ListHeaderTemplateProperty =
            DependencyProperty.Register("ListHeaderTemplate", typeof(DataTemplate), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region ListFooter DependencyProperty

        /// <summary>
        /// The ListFooter property. Will be used as the first scrollItem in the list.
        /// </summary>
        public object ListFooter
        {
            get { return (object)GetValue(ListFooterProperty); }
            set { SetValue(ListFooterProperty, value); }
        }

        /// <summary>
        /// The ListFooter DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ListFooterProperty =
            DependencyProperty.Register("ListFooter", typeof(object), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region ListFooterTemplate DependencyProperty

        /// <summary>
        /// The ListFooterTemplate provides the template for the ListFooter.
        /// </summary>
        public DataTemplate ListFooterTemplate
        {
            get { return (DataTemplate)GetValue(ListFooterTemplateProperty); }
            set { SetValue(ListFooterTemplateProperty, value); }
        }

        /// <summary>
        /// The ListFooterTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ListFooterTemplateProperty =
            DependencyProperty.Register("ListFooterTemplate", typeof(DataTemplate), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region GroupHeaderTemplate DependencyProperty

        /// <summary>
        /// The GroupHeaderTemplate provides the template for the groups in the items view.
        /// </summary>
        public DataTemplate GroupHeaderTemplate
        {
            get { return (DataTemplate)GetValue(GroupHeaderProperty); }
            set { SetValue(GroupHeaderProperty, value); }
        }

        /// <summary>
        /// The GroupHeaderTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty GroupHeaderProperty =
            DependencyProperty.Register("GroupHeaderTemplate", typeof(DataTemplate), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region GroupFooterTemplate DependencyProperty

        /// <summary>
        /// The GroupFooterTemplate provides the template for the groups in the items view.
        /// </summary>
        public DataTemplate GroupFooterTemplate
        {
            get { return (DataTemplate)GetValue(GroupFooterProperty); }
            set { SetValue(GroupFooterProperty, value); }
        }

        /// <summary>
        /// The GroupFooterTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty GroupFooterProperty =
            DependencyProperty.Register("GroupFooterTemplate", typeof(DataTemplate), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region ItemTemplate DependencyProperty

        /// <summary>
        /// The ItemTemplate provides the template for the items in the items view.
        /// </summary>
        public DataTemplate ItemTemplate
        {
            get { return (DataTemplate)GetValue(ItemsTemplateProperty); }
            set { SetValue(ItemsTemplateProperty, value); }
        }

        /// <summary>
        /// The ItemTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ItemsTemplateProperty =
            DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region GroupItemTemplate DependencyProperty

        /// <summary>
        /// The GroupItemTemplate specifies the template that will be used in group view mode.
        /// </summary>
        public DataTemplate GroupItemTemplate
        {
            get { return (DataTemplate)GetValue(GroupItemTemplateProperty); }
            set { SetValue(GroupItemTemplateProperty, value); }
        }

        /// <summary>
        /// The GroupItemTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty GroupItemTemplateProperty =
            DependencyProperty.Register("GroupItemTemplate", typeof(DataTemplate), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region GroupItemsPanel DependencyProperty

        /// <summary>
        /// The GroupItemsPanel specifies the panel that will be used in group view mode.
        /// </summary>
        public ItemsPanelTemplate GroupItemsPanel
        {
            get { return (ItemsPanelTemplate)GetValue(GroupItemsPanelProperty); }
            set { SetValue(GroupItemsPanelProperty, value); }
        }

        /// <summary>
        /// The GroupItemsPanel DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty GroupItemsPanelProperty =
            DependencyProperty.Register("GroupItemsPanel", typeof(ItemsPanelTemplate), typeof(LongListSelector), new PropertyMetadata(null));

        #endregion

        #region IsBouncy DependencyProperty

        /// <summary>
        /// Controls whether the list can be (temporarily) scrolled off of the ends.
        /// </summary>
        public bool IsBouncy
        {
            get { return (bool)GetValue(IsBouncyProperty); }
            set { SetValue(IsBouncyProperty, value); }
        }

        /// <summary>
        /// The IsBouncy DependencyProperty
        /// </summary>
        public static readonly DependencyProperty IsBouncyProperty =
            DependencyProperty.Register("IsBouncy", typeof(bool), typeof(LongListSelector), new PropertyMetadata(true));

        #endregion

        #region IsScrolling DependencyProperty

        /// <summary>
        /// Returns true if the user is manipulating the list, or if an inertial animation is taking place.
        /// </summary>
        public bool IsScrolling
        {
            get { return (bool)GetValue(IsScrollingProperty); }
            private set { SetValue(IsScrollingProperty, value); }
        }

        /// <summary>
        /// The IsScrolling DependencyProperty
        /// </summary>
        public static readonly DependencyProperty IsScrollingProperty =
            DependencyProperty.Register("IsScrolling", typeof(bool), typeof(LongListSelector), new PropertyMetadata(false, OnIsScrollingChanged));

        private static void OnIsScrollingChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            LongListSelector control = (LongListSelector)obj;

            if ((bool) e.NewValue)
            {
                VisualStateManager.GoToState(control, "Scrolling", true);
                SafeRaise.Raise(control.ScrollingStarted, obj);
            }
            else
            {
                VisualStateManager.GoToState(control, "NotScrolling", true);
                control.BounceBack(false);
                SafeRaise.Raise(control.ScrollingCompleted, obj);
            }
        }

        #endregion

        #region ShowListHeader DependencyProperty

        /// <summary>
        /// Controls whether or not the ListHeader is shown.
        /// </summary>
        public bool ShowListHeader
        {
            get { return (bool)GetValue(ShowListHeaderProperty); }
            set { SetValue(ShowListHeaderProperty, value); }
        }

        /// <summary>
        /// The ShowListHeader DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ShowListHeaderProperty =
            DependencyProperty.Register("ShowListHeader", typeof(bool), typeof(LongListSelector), new PropertyMetadata(true, OnShowListHeaderChanged));

        private static void OnShowListHeaderChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            LongListSelector control = (LongListSelector)obj;

            if (control.HasListHeader && control._flattenedItems != null)
            {
                if (control.ShowListHeader)
                {
                    control.OnAdd(0, ItemType.ListHeader, null, new object[] {control.ListHeader});
                }
                else
                {
                    control.OnRemove(0, 1);
                }
                control.StopScrolling();
                control.ResetMinMax();
                control.Balance();
                control.BounceBack(true);
            }
        }

        #endregion

        #region ShowListFooter DependencyProperty

        /// <summary>
        /// Controls whether or not the ListFooter is shown.
        /// </summary>
        public bool ShowListFooter
        {
            get { return (bool)GetValue(ShowListFooterProperty); }
            set { SetValue(ShowListFooterProperty, value); }
        }

        /// <summary>
        /// The ShowListFooter DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ShowListFooterProperty =
            DependencyProperty.Register("ShowListFooter", typeof(bool), typeof(LongListSelector), new PropertyMetadata(true, OnShowListFooterChanged));

        private static void OnShowListFooterChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            LongListSelector control = (LongListSelector)obj;

            if (control.HasListFooter && control._flattenedItems != null)
            {
                if (control.ShowListFooter)
                {
                    control.OnAdd(control._flattenedItems.Count, ItemType.ListFooter, null, new object[] { control.ListFooter });
                }
                else
                {
                    control.OnRemove(control._flattenedItems.Count - 1, 1);
                }
                control.StopScrolling();
                control.ResetMinMax();
                control.Balance();
                control.BounceBack(true);
            }
        }

        #endregion

        #region SelectedItem DependencyProperty

        private bool _setSelectionInternal;
        private bool _selectedItemChanged;
        private object[] EmptyList = { };
        private object[] _selectionList = new Object[1];

        /// <summary>
        /// Gets or sets the selected item.
        /// </summary>
        public object SelectedItem
        {
            get { return (object)GetValue(SelectedItemProperty); }
            set { SetValue(SelectedItemProperty, value); }
        }

        /// <summary>
        /// The SelectedItem DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register("SelectedItem", typeof(object), typeof(LongListSelector), new PropertyMetadata(OnSelectedItemChanged));

        private static void OnSelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            ((LongListSelector)obj).OnSelectedItemChanged(e);
        }

        private void OnSelectedItemChanged(DependencyPropertyChangedEventArgs e)
        {
            _selectedItemChanged = true;

            if (!_setSelectionInternal)
            {
                RaiseSelectionChangedEvent(e.NewValue);
            }
        }

        private void RaiseSelectionChangedEvent(object newSelection)
        {
            SelectionChangedEventHandler handler = SelectionChanged;
            if (handler != null)
            {
                _selectionList[0] = newSelection;
                handler(this, new SelectionChangedEventArgs(EmptyList, _selectionList));
            }
        }

        private void SetSelectedItemInternal(object newSelectedItem)
        {          
            _setSelectionInternal = true;
            _selectedItemChanged = false;
            SelectedItem = newSelectedItem;
            if (_selectedItemChanged)
            {
                RaiseSelectionChangedEvent(newSelectedItem);
            }
            _setSelectionInternal = false;
        }

        #endregion

        #region BufferSize DependencyProperty

        /// <summary>
        /// The number of "screens" (as defined by the ActualHeight of the LongListSelector) above and below the visible
        /// items of the list that will be filled with items.
        /// </summary>
        public double BufferSize
        {
            get { return (double)GetValue(BufferSizeProperty); }
            set { SetValue(BufferSizeProperty, value); }
        }

        /// <summary>
        /// The BufferSize DependencyProperty
        /// </summary>
        public static readonly DependencyProperty BufferSizeProperty =
            DependencyProperty.Register("BufferSize", typeof(double), typeof(LongListSelector), new PropertyMetadata(BufferSizeDefault, OnBufferSizeChanged));

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
        private static void OnBufferSizeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            double newValue = (double)e.NewValue;

            if (newValue < 0)
            {
                throw new ArgumentOutOfRangeException("BufferSize");
            }

            ((LongListSelector)obj)._bufferSizeCache = newValue;
        }

        #endregion

        #region MaximumFlickVelocity DependencyProperty

        /// <summary>
        /// The maximum velocity for flicks, in pixels per second.
        /// </summary>
        public double MaximumFlickVelocity
        {
            get { return (double)GetValue(MaximumFlickVelocityProperty); }
            set { SetValue(MaximumFlickVelocityProperty, value); }
        }

        /// <summary>
        /// The MaximumFlickVelocity DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty MaximumFlickVelocityProperty =
            DependencyProperty.Register("MaximumFlickVelocity", typeof(double), typeof(LongListSelector), new PropertyMetadata(MotionParameters.MaximumSpeed, OnMaximumFlickVelocityChanged));

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
        private static void OnMaximumFlickVelocityChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            double newValue = (double)e.NewValue;

            double coercedNewValue = Math.Min(MotionParameters.MaximumSpeed, Math.Max(newValue, 1));

            if (newValue != coercedNewValue)
            {
                ((LongListSelector)obj).MaximumFlickVelocity = MotionParameters.MaximumSpeed;
                throw new ArgumentOutOfRangeException("MaximumFlickVelocity");
            }
        }

        #endregion

        #region DisplayAllGroups DependencyProperty

        /// <summary>
        /// Display all groups whether or not they have items.
        /// </summary>
        public bool DisplayAllGroups
        {
            get { return (bool)GetValue(DisplayAllGroupsProperty); }
            set { SetValue(DisplayAllGroupsProperty, value); }
        }

        /// <summary>
        /// DisplayAllGroups DependencyProperty
        /// </summary>
        public static readonly DependencyProperty DisplayAllGroupsProperty =
            DependencyProperty.Register("DisplayAllGroups", typeof(bool), typeof(LongListSelector), new PropertyMetadata(false, OnDisplayAllGroupsChanged));

        private static void OnDisplayAllGroupsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            LongListSelector lls = (LongListSelector)obj;
            lls._flattenedItems = null;
            if (lls._isLoaded)
            {
                lls.EnsureData();
            }
        }

        #endregion

        /// <summary>
        /// The SelectionChanged event.
        /// </summary>
        public event SelectionChangedEventHandler SelectionChanged;

        /// <summary>
        /// Create a new instance of LongListSelector.
        /// </summary>
        public LongListSelector()
        {
            DefaultStyleKey = typeof(LongListSelector);

            SizeChanged += OnSizeChanged;

            GestureListener listener = GestureService.GetGestureListener(this);
            listener.GestureBegin += listener_GestureBegin;
            listener.GestureCompleted += listener_GestureCompleted;
            listener.DragStarted += listener_DragStarted;
            listener.DragDelta += listener_DragDelta;
            listener.DragCompleted += listener_DragCompleted;
            listener.Flick += listener_Flick;
            listener.Tap += listener_Tap;
            Loaded += LongListSelector_Loaded;
            Unloaded += LongListSelector_Unloaded;            
        }

        /// <summary>
        /// Raised when the user is manipulating the list.
        /// </summary>
        public event EventHandler ScrollingStarted;

        /// <summary>
        /// Raised when the user has finished a drag or a flick completes.
        /// </summary>
        public event EventHandler ScrollingCompleted;

        /// <summary>
        /// Raised when IsBouncy is true and the user has dragged the items down from the top as far as they can go.
        /// </summary>
        public event EventHandler StretchingTop;

        /// <summary>
        /// Raised when IsBouncy is true and the user has dragged the items up from the bottom as far as they can go.
        /// </summary>
        public event EventHandler StretchingBottom;

        /// <summary>
        /// Raised when the user is no longer stretching.
        /// </summary>
        public event EventHandler StretchingCompleted;

        /// <summary>
        /// Indicates that the ContentPresenter with the item is about to be "realized".
        /// </summary>
        public event EventHandler<LinkUnlinkEventArgs> Link;

        /// <summary>
        /// Indicates that the ContentPresenter with the item is being recycled and is becoming "un-realized".
        /// </summary>
        public event EventHandler<LinkUnlinkEventArgs> Unlink;

        /// <summary>
        /// Set to true when the list is flat instead of a group hierarchy.
        /// </summary>
        public bool IsFlatList { get; set; }

        /// <summary>
        /// Instantly jump to the specified item.
        /// </summary>
        /// <param name="item">The item to scroll to.</param>
        public void ScrollTo(object item)
        {
            EnsureData();
            UpdateLayout();

            ContentPresenter contentPresenter;
            int itemIndex = GetResolvedIndex(item, out contentPresenter);

            if (itemIndex != -1)
            {
                StopScrolling();
                _panningTransform.Y = -Canvas.GetTop(contentPresenter);
                Balance();
            }

            itemIndex = GetFlattenedIndex(item);

            if (itemIndex != -1)
            {
                RecycleAllItems();
                ResetMinMax();
                StopScrolling();
                _panningTransform.Y = 0;
                _resolvedFirstIndex = itemIndex;
                Balance();
                _panningTransform.Y = GetCoercedScrollPosition(_panningTransform.Y, false);
            }
        }

        /// <summary>
        /// Animate the scrolling of the list to the specified item. Scrolling speed is capped by MaximumFlickVelocity.
        /// </summary>
        /// <param name="item">The item to scroll to.</param>
        public void AnimateTo(object item)
        {
            EnsureData();
            UpdateLayout();

            ContentPresenter contentPresenter;
            int itemIndex = GetResolvedIndex(item, out contentPresenter);

            if (itemIndex != -1)
            {
                // The item we are scrolling to has already been resolved, so we can set up an animation directly
                // to it.

                double newPosition = GetCoercedScrollPosition(-Canvas.GetTop(contentPresenter), false);
                double delta = -newPosition + _panningTransform.Y;
                double seconds = Math.Abs(delta) / MaximumFlickVelocity;
                IEasingFunction ease = PhysicsConstants.GetEasingFunction(seconds);

                if (_scrollingTowards != -1)
                {
                    _scrollingTowards = -1;
                    // This is the termination of an AnimateTo call where the location was
                    // not know. Use a different ease to keep the animation smooth.
                    ease = new ExponentialEase() { EasingMode = EasingMode.EaseOut };
                }

                IsFlicking = true;
                AnimatePanel(new Duration(TimeSpan.FromSeconds(seconds)), ease, newPosition);
                return;
            }

            itemIndex = GetFlattenedIndex(item);

            if (itemIndex != -1)
            {
                // Since we don't know the pixel position of the item we are scrolling to, we just go
                // in a direction, and stop when the item is resolved.
                _scrollingTowards = itemIndex;
                ScrollTowards();
            }
        }

        /// <summary>
        /// Returns all of the items that are currently in view. This is not the same as the items that
        /// have associated visual elements: there are usually some visuals offscreen. This might be
        /// an empty list if scrolling is happening too quickly.
        /// </summary>
        /// <returns>The items in view.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public ICollection<object> GetItemsInView()
        {
            return GetItemsWithContainers(true, false);
        }

        /// <summary>
        /// Used to return either containers or items for either all items with containers or just the 
        /// visible ones, as specified by the parameters. 
        /// </summary>
        /// <param name="onlyItemsInView">When true, will return values for only items that are in view.</param>
        /// <param name="getContainers">When true, will return the containers rather than the items.</param>
        /// <returns>A collection of values as specified above.</returns>
        public ICollection<object> GetItemsWithContainers(bool onlyItemsInView, bool getContainers)
        {
            int start = onlyItemsInView ? _screenFirstIndex : _resolvedFirstIndex;
            int count = onlyItemsInView ? _screenCount : _resolvedCount;

            object[] items = new object[count];

            for (int index = start; index < start + count; ++index)
            {
                items[index - start] = getContainers ? _flattenedItems[index].ContentPresenter : _flattenedItems[index].Item;
            }
        
            return items;
        }

        private bool IsPanning
        {
            get { return _isPanning; }
            set
            {
                _isPanning = value;
                IsScrolling = IsPanning || IsFlicking;
            }
        }

        private bool IsFlicking
        {
            get { return _isFlicking; }
            set
            {
                _isFlicking = value;
                IsScrolling = IsPanning || IsFlicking;
            }
        }

        private bool IsStretching
        {
            get { return _isStretching; }
            set
            {
                if (_isStretching != value)
                {
                    _isStretching = value;
                    if (_isStretching)
                    {
                        if (_dragTarget < _minimumPanelScroll)
                        {
                            SafeRaise.Raise(StretchingBottom, this);
                        }
                        else
                        {
                            SafeRaise.Raise(StretchingTop, this);
                        }
                    }
                    else
                    {
                        SafeRaise.Raise(StretchingCompleted, this);
                    }
                }
            }
        }

        private bool HasListHeader { get { return ListHeaderTemplate != null || ListHeader is UIElement; } }

        private bool HasListFooter { get { return ListFooterTemplate != null || ListFooter is UIElement; } }

        void LongListSelector_Loaded(object sender, RoutedEventArgs e)
        {
            _isLoaded = true;

            EnsureData();
        }

        void LongListSelector_Unloaded(object sender, RoutedEventArgs e)
        {
            _isLoaded = false;
            RecycleAllItems();
        }

        /// <summary>
        /// OnApplyTemplate override, used to locate template parts.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            // Find the template parts. Create dummy objects if parts are missing to avoid
            // null checks throughout the code (although we can't escape them completely.)
            _itemsPanel = GetTemplateChild(ItemsPanelName) as Panel ?? new Canvas();
            _panningTransform = GetTemplateChild(PanningTransformName) as TranslateTransform ?? new TranslateTransform();
            _verticalScrollbar = GetTemplateChild(VerticalScrollBarName) as ScrollBar ?? new ScrollBar();

            _panelAnimation = new DoubleAnimation();
            Storyboard.SetTarget(_panelAnimation, _panningTransform);
            Storyboard.SetTargetProperty(_panelAnimation, new PropertyPath("Y"));

            _panelStoryboard = new Storyboard();
            _panelStoryboard.Children.Add(_panelAnimation);
            _panelStoryboard.Completed += PanelStoryboardCompleted;

            Balance();
        }

        /// <summary>
        /// Override of the MeasureOverride function, to capture the available size.
        /// </summary>
        /// <param name="availableSize">The available size.</param>
        /// <returns>The desired size.</returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            _availableSize.Width = availableSize.Width;
            _availableSize.Height = double.PositiveInfinity;

            return base.MeasureOverride(availableSize);
        }

        #region Event handlers

        private void OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            Clip = new RectangleGeometry() { Rect = new Rect(0, 0, e.NewSize.Width, e.NewSize.Height) };

            if (_isLoaded)
            {
                Balance();
            }
        }

        void listener_GestureBegin(object sender, GestureEventArgs e)
        {
            if (IsScrolling)
            {
                _ignoreNextTap = true;
            }

            _gestureStart = DateTime.Now;

            if (_isFlicking)
            {
                _stopTimer.Tick -= _stopTimer_Tick;
                _stopTimer.Tick += _stopTimer_Tick;
                _stopTimer.Start();
            }
        }

        void _stopTimer_Tick(object sender, EventArgs e)
        {
            StopScrolling();
            IsPanning = IsFlicking = false;
        }

        void listener_GestureCompleted(object sender, GestureEventArgs e)
        {
            _stopTimer.Tick -= _stopTimer_Tick;
            _ignoreNextTap = false;
        }

        private void listener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            if (e.Direction != Orientation.Vertical)
            {
                return;
            }

            _stopTimer.Tick -= _stopTimer_Tick;
            _dragTarget = _panningTransform.Y;

            e.Handled = true;
        }

        private void listener_DragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (e.Direction != Orientation.Vertical)
            {
                return;
            }

            TimeSpan elapsed = DateTime.Now - _gestureStart;

            e.Handled = true;

            if (elapsed > _flickStopWaitTime || Math.Sign(e.VerticalChange) != Math.Sign(_lastFlickVelocity))
            {
                IsPanning = true;
                IsFlicking = false;

                if (_firstDragDuringFlick)
                {
                    StopScrolling();
                    _firstDragDuringFlick = false;
                }
                else
                {
                    AnimatePanel(_panDuration, _panEase, _dragTarget += e.VerticalChange);
                    IsStretching = IsBouncy && (GetCoercedScrollPosition(_dragTarget, true) != _dragTarget);
                }
            }
        }

        private void listener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            if (e.Direction != Orientation.Vertical)
            {
                return;
            }

            IsPanning = false;
            IsStretching = false;

            e.Handled = true;
        }

        private void listener_Flick(object sender, FlickGestureEventArgs e)
        {
            if (e.Direction != Orientation.Vertical)
            {
                return;
            }

            _stopTimer.Tick -= _stopTimer_Tick;
            double vMax = MaximumFlickVelocity;

            _lastFlickVelocity = Math.Min(vMax, Math.Max(e.VerticalVelocity, -vMax));

            Point velocity = new Point(0, _lastFlickVelocity);
            double flickDuration = PhysicsConstants.GetStopTime(velocity);
            Point flickEndPoint = PhysicsConstants.GetStopPoint(velocity);
            IEasingFunction flickEase = PhysicsConstants.GetEasingFunction(flickDuration);

            AnimatePanel(new Duration(TimeSpan.FromSeconds(flickDuration)), flickEase, _panningTransform.Y + flickEndPoint.Y);

            IsFlicking = true;
            _firstDragDuringFlick = true;
            _scrollingTowards = -1; 
            e.Handled = true;
        }

        void listener_Tap(object sender, GestureEventArgs e)
        {
            StopScrolling();
            IsPanning = IsFlicking = false;
        }

        private void StopScrolling()
        {
            double position = Math.Round(_panningTransform.Y);
            StopAnimation();
            _panningTransform.Y = position;
            _stopTimer.Tick -= _stopTimer_Tick;
            _scrollingTowards = -1;
        }

        private void GroupHeaderTap(object sender, GestureEventArgs e)
        {
            _stopTimer.Tick -= _stopTimer_Tick;

            if (!_ignoreNextTap)
            {
                DisplayGroupView();
            }
        }

        private void OnItemTap(object sender, GestureEventArgs e)
        {
            if (!_ignoreNextTap)
            {
                ContentPresenter cp = (ContentPresenter)sender;
                SetSelectedItemInternal(cp.Content);
            }
        }

        private void HandleGesture(object sender, GestureEventArgs e)
        {
            e.Handled = true;
        }

        #endregion

        private bool IsReady() { return _itemsPanel != null && ItemsSource != null && ActualHeight > 0; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        private void Balance()
        {
            if (!IsReady() || _flattenedItems.Count == 0)
            {
                // See comment in the call below. Necessary here for when the last item is removed.
                CollapseRecycledElements();
                _resolvedFirstIndex = _resolvedCount = _screenFirstIndex = _screenCount = 0;
                return;
            }

            double actualHeight = ActualHeight;
            double viewportTop = -(_bufferSizeCache * actualHeight);
            double viewportBottom = (_bufferSizeCache + 1) * actualHeight;
            double scrollPosition = _panningTransform.Y;

            ContentPresenter cc;
            double top = 0, bottom = 0;

            if (_resolvedCount > 0)
            {
                // Remove first?

                cc = FirstResolved.ContentPresenter;

                top = Canvas.GetTop(cc);
                bottom = top + cc.DesiredSize.Height;

                while (_resolvedCount > 0 && bottom + scrollPosition < viewportTop)
                {
                    RecycleFirst();

                    if (_resolvedCount > 0)
                    {
                        cc = FirstResolved.ContentPresenter;
                        top = Canvas.GetTop(cc);
                        bottom = top + cc.DesiredSize.Height;
                    }
                }

                // Remove last?

                if (_resolvedCount > 0)
                {
                    cc = LastResolved.ContentPresenter;
                    top = Canvas.GetTop(cc);
                    bottom = top + cc.DesiredSize.Height;

                    while (_resolvedCount > 0 && top + scrollPosition > viewportBottom)
                    {
                        RecycleLast();

                        if (_resolvedCount > 0)
                        {
                            cc = LastResolved.ContentPresenter;
                            top = Canvas.GetTop(cc);
                            bottom = top + cc.DesiredSize.Height;
                        }
                    }
                }

                if (_resolvedCount == 0)
                {
                    ResetMinMax();
                }
            }

            // Empty list?
            bool appendExtra = _resolvedCount == 0 && _resolvedFirstIndex == 0;

            if (_resolvedCount == 0)
            {
                //Debug.WriteLine("Adding first element");
                _resolvedFirstIndex = Math.Max(0, Math.Min(_resolvedFirstIndex, _flattenedItems.Count - 1));

                var t = _flattenedItems[_resolvedFirstIndex];
                cc = GetAndAddElementFor(t);
                cc.SetExtraData(_resolvedFirstIndex, cc.DesiredSize.Height);
                top = 0;
                Canvas.SetTop(cc, top);
                bottom = cc.DesiredSize.Height;

                if (_resolvedFirstIndex == 0)
                {
                    _maximumPanelScroll = 0;
                }
            }

            // Prepend?

            cc = FirstResolved.ContentPresenter;
            top = Canvas.GetTop(cc);
            bottom = top + cc.DesiredSize.Height;

            if (top + scrollPosition >= viewportTop && _resolvedFirstIndex == 0)
            {
                _maximumPanelScroll = -top;
                BrakeIfGoingTooFar();
            }
            else
            {
                while (top + scrollPosition >= viewportTop && _resolvedFirstIndex > 0)
                {
                    appendExtra = false;

                    _resolvedFirstIndex = Math.Max(0, Math.Min(_resolvedFirstIndex, _flattenedItems.Count - 1));
                    var t = _flattenedItems[--_resolvedFirstIndex];
                    //Debug.WriteLine("Adding {0}", t.Item);
                    cc = GetAndAddElementFor(t);
                    cc.SetExtraData(_resolvedFirstIndex, cc.DesiredSize.Height);
                    bottom = top;
                    top = bottom - cc.DesiredSize.Height;
                    Canvas.SetTop(cc, top);

                    if (_resolvedFirstIndex == 0)
                    {
                        _maximumPanelScroll = -top;
                         BrakeIfGoingTooFar();
                    }
                }
            }

            // Append?

            cc = LastResolved.ContentPresenter;
            top = Canvas.GetTop(cc);
            bottom = top + cc.DesiredSize.Height;

            if (appendExtra)
            {
                // If we went to the top of the list, generate extra items so that we don't need to generate them
                // as soon as scrolling starts.
                viewportBottom += ActualHeight * _bufferSizeCache;
            }

            while (bottom + scrollPosition <= viewportBottom && _resolvedFirstIndex + _resolvedCount < _flattenedItems.Count)
            {
                _resolvedFirstIndex = Math.Max(0, Math.Min(_resolvedFirstIndex, _flattenedItems.Count - 1));
                var t = _flattenedItems[_resolvedFirstIndex + _resolvedCount];
                //Debug.WriteLine("Adding {0}", t.Item);
                cc = GetAndAddElementFor(t);
                cc.SetExtraData(_resolvedFirstIndex + _resolvedCount - 1, cc.DesiredSize.Height);
                top = bottom;
                Canvas.SetTop(cc, top);
                bottom = top + cc.DesiredSize.Height;
            }

            if (_resolvedFirstIndex + _resolvedCount == _flattenedItems.Count)
            {
                _minimumPanelScroll = ActualHeight - bottom;
                if (_minimumPanelScroll > _maximumPanelScroll)
                {
                    _minimumPanelScroll = _maximumPanelScroll;
                }
                BrakeIfGoingTooFar();
            }

            // Determine which items are on the screen

            _screenFirstIndex = 0;
            _screenCount = 0;

            for (int itemIndex = _resolvedFirstIndex; itemIndex < _resolvedFirstIndex + _resolvedCount; ++itemIndex)
            {
                ContentPresenter cp = _flattenedItems[itemIndex].ContentPresenter;
                top = Canvas.GetTop(cp) + scrollPosition;
                bottom = top + cp.DesiredSize.Height;

                if ((top >= 0 && top <= ActualHeight) || (top < 0 && bottom > 0))
                {
                    if (_screenCount == 0)
                    {
                        _screenFirstIndex = itemIndex;
                    }
                    ++_screenCount;
                }
                else if (_screenCount != 0)
                {
                    break;
                }
            }

            // Adjust the scrollbar

            double max = Math.Max(1, _flattenedItems.Count - _screenCount);
            _verticalScrollbar.Maximum = max;
            _verticalScrollbar.Value = Math.Min(max, _screenFirstIndex);
            if (Math.Abs(_screenCount - _verticalScrollbar.Value) > 1)
            {
                _verticalScrollbar.ViewportSize = Math.Max(1, _screenCount);
            }

            // This must be done to ensure proper functionality of controls, e.g. Button.
            // It ensures that only items left in the recycle bin get collapsed, since
            // collapsing items and then immediately making them visible can have strange
            // effects, e.g. with a Button.Click on the stack.
            CollapseRecycledElements();

            // When AnimateTo is called, but the location of the item is not know (because it is not resolved) then
            // the list is just scrolled in the right direction until the item is discovered to be in the resolved 
            // items list.
            if (_scrollingTowards >= _resolvedFirstIndex && _scrollingTowards < _resolvedFirstIndex + _resolvedCount)
            {
                // Since the specified item now has a known location, scroll to it.
                AnimateTo(_flattenedItems[_scrollingTowards].Item);
            }
        }

        private ItemTuple FirstResolved
        {
            get
            {
                return _flattenedItems[_resolvedFirstIndex];
            }
        }

        private ItemTuple LastResolved
        {
            get
            {
                int index = _resolvedFirstIndex + _resolvedCount - 1;
                return _flattenedItems[index];
            }
        }

        private void RecycleFirst()
        {
            if (_resolvedCount > 0)
            {
                var t = _flattenedItems[_resolvedFirstIndex++];
                RemoveAndAddToRecycleBin(t);
            }
        }

        private void RecycleLast()
        {
            if (_resolvedCount > 0)
            {
                var t = _flattenedItems[_resolvedFirstIndex + _resolvedCount - 1];
                RemoveAndAddToRecycleBin(t);
            }
        }

        private void RemoveAndAddToRecycleBin(ItemTuple tuple)
        {
            ContentPresenter cp = tuple.ContentPresenter;

            switch (tuple.ItemType)
            {
                case ItemType.Item:
                    _recycledItems.Push(cp);
                    break;
                case ItemType.GroupHeader:
                    _recycledGroupHeaders.Push(cp);
                    break;
                case ItemType.GroupFooter:
                    _recycledGroupFooters.Push(cp);
                    break;
                case ItemType.ListHeader:
                    Debug.Assert(_recycledListHeader == null);
                    _recycledListHeader = cp;
                    break;
                case ItemType.ListFooter:
                    Debug.Assert(_recycledListFooter == null);
                    _recycledListFooter = cp;
                    break;
            }

            EventHandler<LinkUnlinkEventArgs> handler = Unlink;
            if (handler != null)
            {
                handler(this, new LinkUnlinkEventArgs(cp));
            }
            tuple.ContentPresenter = null;
            cp.Content = null;
            cp.SetExtraData(-1, 0);

            --_resolvedCount;
        }

        private void CollapseRecycledElements()
        {
            foreach (ContentPresenter cp in _recycledItems)
            {
                cp.Visibility = Visibility.Collapsed;
            }

            foreach (ContentPresenter cp in _recycledGroupHeaders)
            {
                cp.Visibility = Visibility.Collapsed;
            }

            foreach (ContentPresenter cp in _recycledGroupFooters)
            {
                cp.Visibility = Visibility.Collapsed;
            }

            if (_recycledListHeader != null)
            {
                _recycledListHeader.Visibility = Visibility.Collapsed;
            }

            if (_recycledListFooter != null)
            {
                _recycledListFooter.Visibility = Visibility.Collapsed;
            }
        }

        private void EmptyRecycleBin()
        {
            if (_recycledItems != null)
            {
                _recycledItems.Clear();
            }

            if (_recycledGroupHeaders != null)
            {
                _recycledGroupHeaders.Clear();
            }

            if (_recycledGroupFooters != null)
            {
                _recycledGroupFooters.Clear();
            }

            _recycledListHeader = null;
            _recycledListFooter = null;
        }

        private void RecycleAllItems()
        {
            while (_resolvedCount > 0)
            {
                RecycleFirst();
            }

            _resolvedFirstIndex = 0;
        }

        private ContentPresenter GetAndAddElementFor(ItemTuple tuple)
        {
            ContentPresenter cp = null;
            bool isNew = false;

            switch (tuple.ItemType)
            {
                case ItemType.Item:
                    if (_recycledItems.Count > 0)
                    {
                        cp = _recycledItems.Pop();
                    }
                    else
                    {
                        isNew = true;
                        cp = new ContentPresenter();
                        cp.ContentTemplate = ItemTemplate;

                        GestureService.GetGestureListener(cp).Tap += OnItemTap;
                    }
                    break;
                case ItemType.GroupHeader:
                    if (_recycledGroupHeaders.Count > 0)
                    {
                        cp = _recycledGroupHeaders.Pop();
                    }
                    else
                    {
                        isNew = true;
                        cp = new ContentPresenter();
                        cp.ContentTemplate = GroupHeaderTemplate;

                        GestureService.GetGestureListener(cp).Tap += GroupHeaderTap;
                    }
                    break;
                case ItemType.GroupFooter:
                    if (_recycledGroupFooters.Count > 0)
                    {
                        cp = _recycledGroupFooters.Pop();
                    }
                    else
                    {
                        isNew = true;
                        cp = new ContentPresenter();
                        cp.ContentTemplate = GroupFooterTemplate;
                    }
                    break;
                case ItemType.ListHeader:
                    if (_recycledListHeader != null)
                    {
                        cp = _recycledListHeader;
                        _recycledListHeader = null;
                    }
                    else
                    {
                        isNew = true;
                        cp = new ContentPresenter();
                        cp.ContentTemplate = ListHeaderTemplate;
                    }
                    break;
                case ItemType.ListFooter:
                    if (_recycledListFooter != null)
                    {
                        cp = _recycledListFooter;
                        _recycledListFooter = null;
                    }
                    else
                    {
                        isNew = true;
                        cp = new ContentPresenter();
                        cp.ContentTemplate = ListFooterTemplate;
                    }
                    break;
                default:
                    break;
            }

            if (isNew)
            {
                cp.CacheMode = new BitmapCache();
                _itemsPanel.Children.Add(cp);
                cp.SizeChanged += new SizeChangedEventHandler(OnItemSizeChanged);
            }

            if (cp != null)
            {
                if (cp.Width != _availableSize.Width)
                {
                    cp.Width = _availableSize.Width;
                }
                cp.Content = tuple.Item;
                cp.Visibility = Visibility.Visible;
            }

            EventHandler<LinkUnlinkEventArgs> handler = Link;
            if (handler != null)
            {
                handler(this, new LinkUnlinkEventArgs(cp));
            }
            
            tuple.ContentPresenter = cp;
            cp.Measure(_availableSize);            
            ++_resolvedCount;
            return cp;
        }

        private void OnItemSizeChanged(object sender, SizeChangedEventArgs e)
        {
            // This will get called when items get containers as well as when an item that already
            // have containers are changed. The initial container size is saved after the Measure
            // call in Balance, and updated here if necessary. It is compared to the incoming size
            // to see if the size of the container really changed or if the event is being raised
            // because the container was recycled.

            ContentPresenter cp = sender as ContentPresenter;
            double delta = e.NewSize.Height - e.PreviousSize.Height;
            _minimumPanelScroll -= delta;

            if (cp != null)
            {
                int index;
                double lastDesiredHeight;
                cp.GetExtraData(out index, out lastDesiredHeight);

                if (lastDesiredHeight == e.NewSize.Height)
                {
                    return;
                }
                
                cp.SetExtraData(index, e.NewSize.Height);

                if (index < _screenFirstIndex)
                {
                    // Adjust the item that changed and all previous items
                    while (index >= _resolvedFirstIndex)
                    {
                        double top = Canvas.GetTop(_flattenedItems[index].ContentPresenter);
                        top -= delta;
                        Canvas.SetTop(_flattenedItems[index].ContentPresenter, top);
                        --index;
                    }
                }
                else
                {
                    // Adjust items AFTER the item that changed
                    int resolvedLastIndex = _resolvedFirstIndex + _resolvedCount - 1;
                    ++index; // The item that changed size doesn't have to move
                    while (index <= resolvedLastIndex)
                    {
                        double top = Canvas.GetTop(_flattenedItems[index].ContentPresenter);
                        top += delta;
                        Canvas.SetTop(_flattenedItems[index].ContentPresenter, top);
                        ++index;
                    }
                }

                if (!_balanceNeededForSizeChanged)
                {
                    _balanceNeededForSizeChanged = true;
                    LayoutUpdated += LongListSelector_LayoutUpdated;
                }
            }
        }

        void LongListSelector_LayoutUpdated(object sender, EventArgs e)
        {
            _balanceNeededForSizeChanged = false;
            LayoutUpdated -= LongListSelector_LayoutUpdated;

            Balance();
        }

        private void EnsureData()
        {
            if (_flattenedItems == null || _flattenedItems.Count == 0)
            {
                FlattenData();
                Balance();
            }
        }

        private void FlattenData()
        {
            bool groupHeaderExists = GroupHeaderTemplate != null;
            bool groupFooterExists = GroupFooterTemplate != null;
            bool displayAllGroups = DisplayAllGroups;

            _flattenedItems = new List<ItemTuple>();
            _firstGroup = null;

            SetSelectedItemInternal(null);

            _resolvedFirstIndex = 0;
            _resolvedCount = 0;

            _firstGroup = null;

            if (_panningTransform != null)
            {
                StopAnimation();
                _panningTransform.Y = 0;
                ResetMinMax();
            }
            
            ResetMinMax();

            if (_itemsPanel != null)
            {
                _itemsPanel.Children.Clear();
            }

            EmptyRecycleBin();

            if (_rootCollection != null)
            {
                _rootCollection.CollectionChanged -= OnRootCollectionChanged;
            }
            _rootCollection = null;

            if (_groupCollections != null)
            {
                foreach (INotifyCollectionChanged gc in _groupCollections)
                {
                    if (gc != null)
                    {
                        gc.CollectionChanged -= OnGroupCollectionChanged;
                    }
                }
            }
            _groupCollections = new List<INotifyCollectionChanged>();

            if (ItemsSource == null)
            {
                return;
            }

            if (HasListHeader && ShowListHeader)
            {
                _flattenedItems.Add(new ItemTuple() { ItemType = ItemType.ListHeader, Item = ListHeader });
            }

            foreach (object group in ItemsSource)
            {
                object groupRequiringFooter = null;

                if (IsFlatList)
                {
                    _flattenedItems.Add(new ItemTuple() { ItemType = ItemType.Item, Group = group, Item = group });
                }
                else
                {
                    IEnumerable itemEnumerable = (IEnumerable) group;
                    IEnumerator itemEnumerator = itemEnumerable.GetEnumerator();

                    bool hasItems = itemEnumerator.MoveNext();

                    if (hasItems || displayAllGroups)
                    {
                        if (groupHeaderExists)
                        {
                            _flattenedItems.Add(new ItemTuple() { ItemType = ItemType.GroupHeader, Group = group, Item = group });
                        }

                        if (groupFooterExists)
                        {
                            groupRequiringFooter = group;
                        }

                        if (_firstGroup == null)
                        {
                            _firstGroup = group;
                        }
                    }

                    if (hasItems)
                    {
                        while (hasItems)
                        {
                            _flattenedItems.Add(new ItemTuple() { ItemType = ItemType.Item, Group = group, Item = itemEnumerator.Current });
                            hasItems = itemEnumerator.MoveNext();
                        }
                    }

                    if (groupRequiringFooter != null)
                    {
                        _flattenedItems.Add(new ItemTuple() { ItemType = ItemType.GroupFooter, Group = group, Item = group });
                        groupRequiringFooter = null;
                    }

                    AddGroupNotifyCollectionChanged(group);

                }
            }

            _rootCollection = ItemsSource as INotifyCollectionChanged;
            if (_rootCollection != null)
            {
                _rootCollection.CollectionChanged += OnRootCollectionChanged;
            }

            if (HasListFooter && ShowListFooter)
            {
                _flattenedItems.Add(new ItemTuple() { ItemType = ItemType.ListFooter, Item = ListFooter });
            }

            if (_verticalScrollbar != null)
            {
                _verticalScrollbar.Maximum = _flattenedItems.Count;
            }
        }

        private void AddGroupNotifyCollectionChanged(object group)
        {
            INotifyCollectionChanged groupNCC = group as INotifyCollectionChanged;
            if (groupNCC != null)
            {
                _groupCollections.Add(groupNCC);
                groupNCC.CollectionChanged += OnGroupCollectionChanged;
            }
        }

        private void RemoveGroupNotifyCollectionChanged(object group)
        {
            INotifyCollectionChanged groupNCC = group as INotifyCollectionChanged;
            if (groupNCC != null)
            {
                _groupCollections.Remove(groupNCC);
                groupNCC.CollectionChanged -= OnGroupCollectionChanged;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        void OnRootCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            int headerOffset = HasListHeader && ShowListHeader ? 1 : 0;

            if (IsFlatList)
            {
                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        OnAdd(headerOffset + e.NewStartingIndex, ItemType.Item, null, e.NewItems);
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        OnRemove(headerOffset + e.OldStartingIndex, e.OldItems.Count);
                        break;
                    case NotifyCollectionChangedAction.Replace:
                        if (e.NewItems.Count != 1)
                        {
                            throw new NotSupportedException();
                        }
                        OnReplace(headerOffset + e.NewStartingIndex, e.NewItems[0]);
                        break;
                    case NotifyCollectionChangedAction.Reset:
                        _flattenedItems = null;
                        EnsureData();
                        break;
                }
            }
            else
            {
                bool displayAllGroups = DisplayAllGroups;

                int groupHeaderOffset = GroupHeaderTemplate != null ? 1 : 0;
                int groupFooterOffset = GroupFooterTemplate != null ? 1 : 0;

                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        {
                            IList groupList = (IList)ItemsSource;
                            object groupAtIndex = e.NewStartingIndex < groupList.Count ? groupList[e.NewStartingIndex] : null;
                            int offset = groupAtIndex != null ? GetGroupOffset(groupAtIndex) : groupList.Count;
                            foreach (object group in e.NewItems)
                            {
                                AddGroupNotifyCollectionChanged(group);

                                IList itemsList = GetItemsInGroup(group);
                                if (itemsList.Count > 0 || displayAllGroups)
                                {
                                    if (groupHeaderOffset == 1)
                                    {
                                        OnAdd(offset, ItemType.GroupHeader, group, new object[] { group });
                                        ++offset;
                                    }

                                    if (itemsList.Count > 0)
                                    {
                                        OnAdd(offset, ItemType.Item, group, itemsList);
                                        offset += itemsList.Count;
                                    }

                                    if (groupFooterOffset == 1)
                                    {
                                        OnAdd(offset, ItemType.GroupFooter, group, new object[] { group });
                                        ++offset;
                                    }
                                }
                            }
                        }
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        {
                            foreach (object group in e.OldItems)
                            {
                                RemoveGroupNotifyCollectionChanged(group);
                                IList itemsList = GetItemsInGroup(group);
                                int offset = GetGroupOffset(group);
                                int count = itemsList.Count;
                                if (displayAllGroups || itemsList.Count > 0)
                                {
                                    count += groupHeaderOffset + groupFooterOffset;
                                }

                                OnRemove(offset, count);
                            }
                        }
                        break;
                    case NotifyCollectionChangedAction.Replace:
                        throw new NotSupportedException();
                    case NotifyCollectionChangedAction.Reset:
                        _flattenedItems = null;
                        EnsureData();
                        break;
                }

            }

            ResetMinMax();
            Balance();
            if (BounceBack(true))
            {
                // The group could have been inserted at the beginning of the list, when 
                // there are not enough items to fill the screen.
                Balance();
            }
        }

        private static IList GetItemsInGroup(object group)
        {
            IList itemsList = group as IList;
            if (itemsList != null)
            {
                return itemsList;
            }

            List<object> items = new List<object>();

            IEnumerator itemEnum = ((IEnumerable)group).GetEnumerator();
            bool hasItems = itemEnum.MoveNext();

            while (hasItems)
            {
                items.Add(itemEnum.Current);
                hasItems = itemEnum.MoveNext();
            }

            return items;
        }

        /// <summary>
        /// Returns true if the group has no items
        /// </summary>
        /// <param name="group">The group to check.</param>
        /// <returns>True if the group has no items.</returns>
        private static bool IsGroupEmpty(object group)
        {
            IList itemsList = group as IList;
            if (itemsList != null)
            {
                return itemsList.Count == 0;
            }

            IEnumerator itemEnum = ((IEnumerable)group).GetEnumerator();
            return !itemEnum.MoveNext();
        }

        void OnGroupCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            object group = sender;
            int groupHeaderOffset = GroupHeaderTemplate != null ? 1 : 0;
            int groupFooterOffset = GroupFooterTemplate != null ? 1 : 0;
            bool displayAllGroups = DisplayAllGroups;
            int itemsInGroupCount;
            
            int offset = GetGroupOffset(group, out itemsInGroupCount);

            IList groupList = group as IList;
            if (!displayAllGroups && groupList != null && e.Action == NotifyCollectionChangedAction.Add && groupList.Count == e.NewItems.Count)
            {
                if (groupHeaderOffset == 1)
                {
                    OnAdd(offset, ItemType.GroupHeader, group, new object[] { group });                    
                }

                if (groupFooterOffset == 1)
                {
                    OnAdd(offset + groupHeaderOffset, ItemType.GroupFooter, group, new object[] { group });
                }
            }

            offset += groupHeaderOffset;
          
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    OnAdd(e.NewStartingIndex + offset, ItemType.Item, group, e.NewItems);
                    break;
                case NotifyCollectionChangedAction.Remove:
                    {
                        int count = e.OldItems.Count;
                        if (IsGroupEmpty(group) && !displayAllGroups)
                        {
                            // The last items in the group are going away; remove the group, too.
                            offset -= groupHeaderOffset;
                            count += groupHeaderOffset + groupFooterOffset;
                        }
                        OnRemove(e.OldStartingIndex + offset, count);
                    }
                    break;
                case NotifyCollectionChangedAction.Replace:
                    if (e.NewItems.Count != 1)
                    {
                        throw new NotSupportedException();
                    }
                    OnReplace(offset + e.NewStartingIndex, e.NewItems[0]);
                    break;
                case NotifyCollectionChangedAction.Reset:
                    if (DisplayAllGroups)
                    {
                        OnRemove(offset, itemsInGroupCount);
                    }
                    else if (itemsInGroupCount > 0)
                    {
                        OnRemove(offset - groupHeaderOffset, itemsInGroupCount + groupHeaderOffset + groupFooterOffset);
                    }
                    break;
            }

            ResetMinMax();
            Balance();
            if (BounceBack(true))
            {
                // The group could have been inserted at the beginning of the list, when 
                // there are not enough items to fill the screen.
                Balance();
            }
        }

        private int GetGroupOffset(object group)
        {
            int listHeaderOffset = HasListHeader && ShowListHeader ? 1 : 0;
            // int listFooterOffset = HasListFooter && ShowListFooter ? 1 : 0;

            bool displayAll = DisplayAllGroups;
            int groupHeaderOffset = GroupHeaderTemplate != null ? 1 : 0;
            int groupFooterOffset = GroupFooterTemplate != null ? 1 : 0;

            int offset = listHeaderOffset;
            
            foreach (var g in ItemsSource)
            {
                if (g.Equals(group))
                {
                    break;
                }

                int groupCount = 0;

                var groupList = g as IList;
                if (groupList != null)
                {
                    groupCount = groupList.Count;
                }
                else
                {
                    var groupEnum = g as IEnumerable;
                    if (groupEnum != null)
                    {
                        IEnumerator enumerator = groupEnum.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            ++groupCount;
                        }
                    }
                }

                if (displayAll || groupCount > 0)
                {
                    offset += groupHeaderOffset + groupFooterOffset;
                }

                offset += groupCount;
            }

            return offset;
        }

        // Returns the first offset after all preceding groups. This could be 
        // the position of the group header, the first group item (if there is 
        // no header) or the place where the group should be inserted.
        // We have to count the items this way because this is used when clearing
        // a group, and the items will already have been removed from the group so
        // we can't get the count from there.
        private int GetGroupOffset(object group, out int itemsInGroupCount)
        {
            int offset = GetGroupOffset(group);

            int lastGroupOffset = offset;
            itemsInGroupCount = 0;
            while (lastGroupOffset < _flattenedItems.Count && group.Equals(_flattenedItems[lastGroupOffset].Group))
            {
                if (_flattenedItems[lastGroupOffset].ItemType == ItemType.Item)
                {
                    ++itemsInGroupCount;
                }

                ++lastGroupOffset;               
            }

            return offset;
        }

        private void OnAdd(int startingIndex, ItemType itemType, object group, IList newItems)
        {
            int resolvedLastIndex = _resolvedFirstIndex + _resolvedCount - 1;

            // Perform the Add operation

            ItemTuple[] newData = new ItemTuple[newItems.Count];
            for (int index = 0; index < newItems.Count; ++index)
            {
                newData[index] = new ItemTuple() { ItemType = itemType, Group = group, Item = newItems[index] };
            }

            if (startingIndex <= _resolvedFirstIndex || startingIndex > resolvedLastIndex)
            {
                // If the operation is completely outside the bounds of the resolved items, then it can just happen.
                
                if (startingIndex <= _resolvedFirstIndex)
                {
                    if (_resolvedCount > 0)
                    {
                        _resolvedFirstIndex += newItems.Count;
                    }
                    else
                    {
                        _resolvedFirstIndex = 0;
                    }
                }
            }
            else if (startingIndex < _screenFirstIndex)
            {
                int removeCount = startingIndex - _resolvedFirstIndex + 1;

                while (removeCount-- > 0)
                {
                    RecycleFirst();
                }

                _resolvedFirstIndex += newItems.Count;
            }
            else
            {
                int removeCount = _resolvedCount - startingIndex + _resolvedFirstIndex;

                while (removeCount-- > 0)
                {
                    RecycleLast();
                }
            }

            // Perform the Add operation
            _flattenedItems.InsertRange(startingIndex, newData);
        }

        private void OnRemove(int startingIndex, int count)
        {
            int endIndex = startingIndex + count - 1;

            int resolvedLastIndex = _resolvedFirstIndex + _resolvedCount - 1;

            // If the operation is completely outside the bounds of the resolved items,
            // then it can just happen.
            if (endIndex < _resolvedFirstIndex || startingIndex > resolvedLastIndex)
            {
                if (startingIndex < _resolvedFirstIndex)
                {
                    if (startingIndex + count - 1 < _resolvedFirstIndex)
                    {
                        _resolvedFirstIndex -= count;
                    }
                }
            }
            else 
            {
                if (startingIndex >= _screenFirstIndex)
                {
                    // The deletion point is either on the screen or after the screen.

                    int removeCount = resolvedLastIndex - startingIndex + 1;

                    while (removeCount-- > 0)
                    {
                        RecycleLast();
                    }
                }
                else
                {
                    // The deletion starts before the screen

                    int recycleCount = Math.Min(_resolvedCount, startingIndex - _resolvedFirstIndex + 1);

                    while (recycleCount-- > 0)
                    {
                        RecycleFirst();
                    }

                    _resolvedFirstIndex -= count;
                }
            }

            // Perform the remove operation
            _flattenedItems.RemoveRange(startingIndex, count);
        }

        /// <summary>
        /// Replaces a single object in a group
        /// </summary>
        /// <param name="index">The global index of the item.</param>
        /// <param name="item">The new item.</param>
        private void OnReplace(int index, object item)
        {
            int resolvedLastIndex = _resolvedFirstIndex + _resolvedCount - 1;

            if (index >= _resolvedFirstIndex && index <= resolvedLastIndex)
            {
                if (index < _resolvedFirstIndex)
                {
                    int count = _resolvedFirstIndex - index + 1;
                    while (count-- > 0)
                    {
                        RecycleFirst();
                    }
                }
                else
                {
                    int count = resolvedLastIndex - index + 1;
                    while (count-- > 0)
                    {
                        RecycleLast();
                    }
                }
            }

            _flattenedItems[index].Item = item;
        }


        private void ResetMinMax()
        {
            _minimumPanelScroll = float.MinValue;
            _maximumPanelScroll = float.MaxValue;
        }

        private void AnimatePanel(Duration duration, IEasingFunction ease, double to)
        {
            // Be sure not to run past the first or last items
            double newTo = GetCoercedScrollPosition(to, IsBouncy);
            if (to != newTo)
            {
                // Adjust the duration
                double originalDelta = Math.Max(Math.Abs(_panningTransform.Y - to), 1);
                double modifiedDelta = Math.Abs(_panningTransform.Y - newTo);
                double factor = modifiedDelta / originalDelta;

                // If factor > 0, the edge has been detected, but it hasn't gone too far yet, so readjust the animation. 
                // If factor < 0, somehow scrolling has gone past the edge already, so snap back.
                duration = factor <= 1 && factor >= 0 && duration.HasTimeSpan ? new Duration(TimeSpan.FromMilliseconds(duration.TimeSpan.Milliseconds * factor)) : _panDuration;

                to = newTo;
            }

            double from = _panningTransform.Y;
            StopAnimation();
            CompositionTarget.Rendering += AnimationPerFrameCallback;

            _panelAnimation.Duration = duration;
            _panelAnimation.EasingFunction = ease;
            _panelAnimation.From = from;
            _panelAnimation.To = to;
            _panelStoryboard.Begin();
            _panelStoryboard.SeekAlignedToLastTick(TimeSpan.Zero);
            _isAnimating = true;
        }

        private void BrakeIfGoingTooFar()
        {
            if (_isAnimating && _panelAnimation.To.HasValue)
            {
                double to = _panelAnimation.To.Value;
                double newTo = GetCoercedScrollPosition(to, IsBouncy);
                if (newTo != _panelAnimation.To.Value)
                {
                    double originalDelta = Math.Max(_panelAnimation.To.Value - _panelAnimation.From.Value, 1);
                    double remainingDelta = newTo - _panningTransform.Y;
                    double factor = remainingDelta / originalDelta;

                    // If factor > 0, the edge has been detected, but it hasn't gone too far yet, so readjust the animation. 
                    // If factor < 0, somehow scrolling has gone past the edge already, so snap back.
                    Duration duration = factor <= 1 && factor >= 0 && _panelAnimation.Duration.HasTimeSpan ? new Duration(TimeSpan.FromMilliseconds(_panelAnimation.Duration.TimeSpan.Milliseconds * factor)) : _panDuration;

                    AnimatePanel(duration, _panelAnimation.EasingFunction, newTo);
                }
            }
        }

        void AnimationPerFrameCallback(object sender, EventArgs e)
        {
            Balance();
        }

        void PanelStoryboardCompleted(object sender, EventArgs e)
        {
            CompositionTarget.Rendering -= AnimationPerFrameCallback;

            if (_scrollingTowards != -1)
            {
                // We are scrolling in a direction towards an item we did not know the position of.
                // We aren't there yet, so keep going in the same direction.
                ScrollTowards();
                return;
            }
            _isAnimating = false;
            IsFlicking = false;
        }

        private void StopAnimation()
        {
            _panelStoryboard.Stop();
            CompositionTarget.Rendering -= AnimationPerFrameCallback;
            _isAnimating = false;
        }

        private bool BounceBack(bool immediately)
        {
            if (_panningTransform == null || _resolvedCount == 0)
            {
                return false;
            }

            double to = _panningTransform.Y;
            double top = Canvas.GetTop(FirstResolved.ContentPresenter);

            double newTo = top > -to ? -top : GetCoercedScrollPosition(to, false);

            if (to != newTo)
            {
                if (immediately)
                {
                    _panningTransform.Y = newTo;
                }
                else
                {
                    AnimatePanel(_panDuration, _panEase, newTo);
                }

                return true;
            }

            return false;
        }

        /// <summary>
        /// Instantly jump to the selected group.
        /// </summary>
        /// <param name="group">The group to jump to</param>
        public void ScrollToGroup(object group)
        {
            double scrollTarget = 0;
            bool foundTarget = false;

            if (group == null)
            {
                return;
            }

            // First check to see if group is already visible
            for (int index = _resolvedFirstIndex; index < _resolvedFirstIndex + _resolvedCount; ++index)
            {
                ContentPresenter cp = _flattenedItems[index].ContentPresenter;
                if (cp.Content != null && cp.Content.Equals(group) && _flattenedItems[index].ItemType == ItemType.GroupHeader)
                {
                    scrollTarget = -Canvas.GetTop(cp);
                    foundTarget = true;
                    break;
                }
                ++index;
            }

            // Just jump to it, and replace the entire list.
            if (!foundTarget)
            {
                int newIndex = GetGroupOffset(group);
                if (newIndex == -1)
                {
                    return;
                }

                if (newIndex != -1)
                {
                    RecycleAllItems();
                    CollapseRecycledElements();
                    _resolvedFirstIndex = newIndex;
                    scrollTarget = 0;
                    ResetMinMax();
                }
            }

            scrollTarget = GetCoercedScrollPosition(scrollTarget, false);
            StopAnimation();
            _panningTransform.Y = scrollTarget;
            Balance();
            
            // Special case first group to include header
            if (group.Equals(_firstGroup))
            {
                _panningTransform.Y = _maximumPanelScroll;
            }

            BounceBack(true);
        }

        private double BounceDistance { get { return ActualHeight / 4; } }

        private double GetCoercedScrollPosition(double value, bool isBouncy)
        {
            double bounceFactor = isBouncy ? BounceDistance : 0;
            return Math.Max(_minimumPanelScroll - bounceFactor, Math.Min(_maximumPanelScroll + bounceFactor, value));
        }

        /// <summary>
        /// Scroll in the direction of an item that has not been resolved.
        /// </summary>
        private void ScrollTowards()
        {
            if (_scrollingTowards == -1)
            {
                return;
            }
            double jump = _scrollingTowards < _resolvedFirstIndex ? 10000000 : -10000000;
            double newPosition = GetCoercedScrollPosition(_panningTransform.Y + jump, false);

            double delta = newPosition - _panningTransform.Y;
            double seconds = Math.Abs(delta) / MaximumFlickVelocity;
            IsFlicking = true;
            AnimatePanel(new Duration(TimeSpan.FromSeconds(seconds)), null, newPosition);
        }

        private int GetFlattenedIndex(object item)
        {
            int count = _flattenedItems.Count;
            for (int index = 0; index < count; ++index)
            {
                if (item == _flattenedItems[index].Item)
                {
                    return index;
                }
            }
            return -1;
        }

        private int GetResolvedIndex(object item, out ContentPresenter contentPresenter)
        {
            if (_resolvedCount > 0)
            {
                for (int index = _resolvedFirstIndex; index < _resolvedFirstIndex + _resolvedCount; ++index)
                {
                    if (_flattenedItems[index].Item == item)
                    {
                        contentPresenter = _flattenedItems[index].ContentPresenter;
                        return index;
                    }
                }
            }

            contentPresenter = null;
            return -1;
        }

        private enum ItemType
        {
            Unknown,
            Item,
            GroupHeader,
            GroupFooter,
            ListHeader,
            ListFooter
        }

        private class ItemTuple
        {
            public ItemType ItemType;
            public object Group;
            public object Item;
            public ContentPresenter ContentPresenter;
        }

        
    //    private void ComputeResolvedFirstAndCount(out int first, out int count)
    //    {
    //        first = -1; count = 0;

    //        bool done = false;

    //        for (int index = 0; index < _flattenedItems.Count; ++index)
    //        {
    //            if (_flattenedItems[index].ContentPresenter != null)
    //            {
    //                if (done)
    //                {
    //                    throw new InvalidOperationException();
    //                }

    //                if (first == -1)
    //                {
    //                    first = index;
    //                }

    //                ++count;
    //            }
    //            else if (first != -1)
    //            {
    //                done = true;
    //            }
    //        }

    //        if (first == -1)
    //        {
    //            first = 0;
    //        }

    //        Debug.WriteLine("Resolved first {0} count {1}", first, count);
    //    }
    }
}
Back to Top