milk-manager /wp-toolkit/Microsoft.Phone.Controls.Toolkit/ListPicker/ListPicker.cs

Language C# Lines 1373
MD5 Hash ab3bec392dfccaf3c5a89b52c0d94445 Estimated Cost $26,337 (why?)
Repository https://bitbucket.org/jeremejevs/milk-manager.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
// (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.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;

namespace Microsoft.Phone.Controls
{
    /// <summary>
    /// Class that implements a flexible list-picking experience with a custom interface for few/many items.
    /// </summary>
    /// <QualityBand>Preview</QualityBand>
    [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This is a complicated control.")]
    [TemplatePart(Name = ItemsPresenterPartName, Type = typeof(ItemsPresenter))]
    [TemplatePart(Name = ItemsPresenterTranslateTransformPartName, Type = typeof(TranslateTransform))]
    [TemplatePart(Name = ItemsPresenterHostPartName, Type = typeof(Canvas))]
    [TemplatePart(Name = MultipleSelectionModeSummaryPartName, Type = typeof(TextBlock))]
    [TemplateVisualState(GroupName = PickerStatesGroupName, Name = PickerStatesNormalStateName)]
    [TemplateVisualState(GroupName = PickerStatesGroupName, Name = PickerStatesHighlightedStateName)]
    [TemplateVisualState(GroupName = PickerStatesGroupName, Name = PickerStatesDisabledStateName)]
    public class ListPicker : ItemsControl
    {
        private const string ItemsPresenterPartName = "ItemsPresenter";
        private const string ItemsPresenterTranslateTransformPartName = "ItemsPresenterTranslateTransform";
        private const string ItemsPresenterHostPartName = "ItemsPresenterHost";
        private const string MultipleSelectionModeSummaryPartName = "MultipleSelectionModeSummary";
        private const string BorderPartName = "Border";

        private const string PickerStatesGroupName = "PickerStates";
        private const string PickerStatesNormalStateName = "Normal";
        private const string PickerStatesHighlightedStateName = "Highlighted";
        private const string PickerStatesDisabledStateName = "Disabled";

        /// <summary>
        /// In Mango, the size of list pickers in expanded mode was given extra offset.
        /// </summary>
        private const double NormalModeOffset = 4;

        private readonly DoubleAnimation _heightAnimation = new DoubleAnimation();
        private readonly DoubleAnimation _translateAnimation = new DoubleAnimation();
        private readonly Storyboard _storyboard = new Storyboard();

        private PhoneApplicationFrame _frame;
        private PhoneApplicationPage _page;
        private FrameworkElement _itemsPresenterHostParent;
        private Canvas _itemsPresenterHostPart;
        private ItemsPresenter _itemsPresenterPart;
        private TranslateTransform _itemsPresenterTranslateTransformPart;
        private bool _updatingSelection;
        private int _deferredSelectedIndex = -1;
        private object _deferredSelectedItem = null;

        private object _frameContentWhenOpened;
        private NavigationInTransition _savedNavigationInTransition;
        private NavigationOutTransition _savedNavigationOutTransition;
        private ListPickerPage _listPickerPage;
        private TextBlock _multipleSelectionModeSummary;
        private Border _border;

        /// <summary>
        /// Whether this list picker has the picker page opened.
        /// </summary>
        private bool _hasPickerPageOpen;

        /// <summary>
        /// Event that is raised when the selection changes.
        /// </summary>
        public event SelectionChangedEventHandler SelectionChanged;

        /// <summary>
        /// Gets or sets the delegate, which is called to summarize a list of selections into a string.
        /// If not implemented, the default summarizing behavior will be used.
        /// If this delegate is implemented, default summarizing behavior can be achieved by returning
        /// null instead of a string.
        /// </summary>
        public Func<IList, string> SummaryForSelectedItemsDelegate
        {
            get { return (Func<IList, string>)GetValue(SummaryForSelectedItemsDelegateProperty); }
            set { SetValue(SummaryForSelectedItemsDelegateProperty, value); }
        }

        /// <summary>
        /// Identifies the SummaryForSelectedItemsDelegate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty SummaryForSelectedItemsDelegateProperty =
            DependencyProperty.Register("SummaryForSelectedItemsDelegate", typeof(Func<IList, string>), typeof(ListPicker), null);

        /// <summary>
        /// Gets or sets the ListPickerMode (ex: Normal/Expanded/Full).
        /// </summary>
        public ListPickerMode ListPickerMode
        {
            get { return (ListPickerMode)GetValue(ListPickerModeProperty); }
            private set { SetValue(ListPickerModeProperty, value); }
        }

        /// <summary>
        /// Identifies the ListPickerMode DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ListPickerModeProperty =
            DependencyProperty.Register("ListPickerMode", typeof(ListPickerMode), typeof(ListPicker), new PropertyMetadata(ListPickerMode.Normal, OnListPickerModeChanged));

        private static void OnListPickerModeChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ListPicker)o).OnListPickerModeChanged((ListPickerMode)e.OldValue, (ListPickerMode)e.NewValue);
        }

        private void OnListPickerModeChanged(ListPickerMode oldValue, ListPickerMode newValue)
        {
            if ((ListPickerMode.Expanded == oldValue))
            {
                if (null != _page)
                {
                    _page.BackKeyPress -= OnPageBackKeyPress;
                    _page = null;
                }

                if (null != _frame)
                {
                    _frame.ManipulationStarted -= OnFrameManipulationStarted;
                    _frame = null;
                }
            }

            if (ListPickerMode.Expanded == newValue)
            {
                // Hook up to frame if not already done
                if (null == _frame)
                {
                    _frame = Application.Current.RootVisual as PhoneApplicationFrame;
                    if (null != _frame)
                    {
                        _frame.AddHandler(ManipulationStartedEvent, new EventHandler<ManipulationStartedEventArgs>(OnFrameManipulationStarted), true);
                    }
                }

                if (null != _frame)
                {
                    _page = _frame.Content as PhoneApplicationPage;
                    if (null != _page)
                    {
                        _page.BackKeyPress += OnPageBackKeyPress;
                    }
                }
            }

            if (ListPickerMode.Full == oldValue)
            {
                ClosePickerPage();
            }
            if (ListPickerMode.Full == newValue)
            {
                OpenPickerPage();
            }

            SizeForAppropriateView(ListPickerMode.Full != oldValue);
            IsHighlighted = (ListPickerMode.Expanded == newValue);
        }


        /// <summary>
        /// Whether the list picker is highlighted.
        /// This occurs when the user is manipulating the box or when in expanded mode.
        /// </summary>
        private bool IsHighlighted
        {
            get { return (bool)GetValue(IsHighlightedProperty); }
            set { SetValue(IsHighlightedProperty, value); }
        }

        private static readonly DependencyProperty IsHighlightedProperty =
            DependencyProperty.Register("IsHighlighted",
                                        typeof(bool),
                                        typeof(ListPicker),
                                        new PropertyMetadata(false, new PropertyChangedCallback(OnIsHighlightedChanged)));

        /// <summary>
        /// Highlight property changed
        /// </summary>
        private static void OnIsHighlightedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            (o as ListPicker).OnIsHighlightedChanged();
        }

        /// <summary>
        /// Highlight property changed
        /// </summary>
        private void OnIsHighlightedChanged()
        {
            UpdateVisualStates(true);
        }


        /// <summary>
        /// Enabled property changed
        /// </summary>
        private static void OnIsEnabledChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            (o as ListPicker).OnIsEnabledChanged();
        }

        /// <summary>
        /// Enabled property changed
        /// </summary>
        private void OnIsEnabledChanged()
        {
            UpdateVisualStates(true);
        }

        /// <summary>
        /// Gets or sets the index of the selected item.
        /// </summary>
        public int SelectedIndex
        {
            get { return (int)GetValue(SelectedIndexProperty); }
            set { SetValue(SelectedIndexProperty, value); }
        }

        /// <summary>
        /// Identifies the SelectedIndex DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty SelectedIndexProperty =
            DependencyProperty.Register("SelectedIndex", typeof(int), typeof(ListPicker), new PropertyMetadata(-1, OnSelectedIndexChanged));

        private static void OnSelectedIndexChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ListPicker)o).OnSelectedIndexChanged((int)e.OldValue, (int)e.NewValue);
        }

        [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "SelectedIndex", Justification = "Property name.")]
        private void OnSelectedIndexChanged(int oldValue, int newValue)
        {
            // Validate new value
            if ((Items.Count <= newValue) ||
                ((0 < Items.Count) && (newValue < 0)) ||
                ((0 == Items.Count) && (newValue != -1)))
            {
                if ((null == Template) && (0 <= newValue))
                {
                    // Can't set the value now; remember it for later
                    _deferredSelectedIndex = newValue;
                    return;
                }
                throw new InvalidOperationException(Properties.Resources.InvalidSelectedIndex);
            }

            // Synchronize SelectedItem property
            if (!_updatingSelection)
            {
                _updatingSelection = true;
                SelectedItem = (-1 != newValue) ? Items[newValue] : null;
                _updatingSelection = false;
            }

            if (-1 != oldValue)
            {
                // Toggle container selection
                ListPickerItem oldContainer = (ListPickerItem)ItemContainerGenerator.ContainerFromIndex(oldValue);
                if (null != oldContainer)
                {
                    oldContainer.IsSelected = false;
                }
            }
        }

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

        /// <summary>
        /// Identifies the SelectedItem DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register("SelectedItem", typeof(object), typeof(ListPicker), new PropertyMetadata(null, OnSelectedItemChanged));

        private static void OnSelectedItemChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ListPicker)o).OnSelectedItemChanged(e.OldValue, e.NewValue);
        }

        [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "SelectedItem", Justification = "Property name.")]
        private void OnSelectedItemChanged(object oldValue, object newValue)
        {
            if (newValue != null && (null == Items || Items.Count == 0))
            {
                if (null == Template)
                {
                    // Can't set the value now; remember it for later
                    _deferredSelectedItem = newValue;
                    return;
                }
                else
                {
                    throw new InvalidOperationException(Properties.Resources.InvalidSelectedItem);
                }
            }

            // Validate new value
            int newValueIndex = (null != newValue) ? Items.IndexOf(newValue) : -1;

            if ((-1 == newValueIndex) && (0 < Items.Count))
            {
                throw new InvalidOperationException(Properties.Resources.InvalidSelectedItem);
            }

            // Synchronize SelectedIndex property
            if (!_updatingSelection)
            {
                _updatingSelection = true;
                SelectedIndex = newValueIndex;
                _updatingSelection = false;
            }

            // Switch to Normal mode or size for current item
            if (ListPickerMode.Normal != ListPickerMode)
            {
                ListPickerMode = ListPickerMode.Normal;
            }
            else
            {
                SizeForAppropriateView(false);
            }

            // Fire SelectionChanged event
            var handler = SelectionChanged;
            if (null != handler)
            {
                IList removedItems = (null == oldValue) ? new object[0] : new object[] { oldValue };
                IList addedItems = (null == newValue) ? new object[0] : new object[] { newValue };
                handler(this, new SelectionChangedEventArgs(removedItems, addedItems));
            }
        }

        private static readonly DependencyProperty ShadowItemTemplateProperty =
            DependencyProperty.Register("ShadowItemTemplate", typeof(DataTemplate), typeof(ListPicker), new PropertyMetadata(null, OnShadowOrFullModeItemTemplateChanged));

        /// <summary>
        /// Gets or sets the DataTemplate used to display each item when ListPickerMode is set to Full.
        /// </summary>
        public DataTemplate FullModeItemTemplate
        {
            get { return (DataTemplate)GetValue(FullModeItemTemplateProperty); }
            set { SetValue(FullModeItemTemplateProperty, value); }
        }

        /// <summary>
        /// Identifies the FullModeItemTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty FullModeItemTemplateProperty =
            DependencyProperty.Register("FullModeItemTemplate", typeof(DataTemplate), typeof(ListPicker), new PropertyMetadata(null, OnShadowOrFullModeItemTemplateChanged));

        private static void OnShadowOrFullModeItemTemplateChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ListPicker)o).OnShadowOrFullModeItemTemplateChanged(/*(DataTemplate)e.OldValue, (DataTemplate)e.NewValue*/);
        }

        private void OnShadowOrFullModeItemTemplateChanged(/*DataTemplate oldValue, DataTemplate newValue*/)
        {
            // Set ActualFullModeItemTemplate accordingly
            SetValue(ActualFullModeItemTemplateProperty, FullModeItemTemplate ?? ItemTemplate);
        }

        private static readonly DependencyProperty ActualFullModeItemTemplateProperty =
            DependencyProperty.Register("ActualFullModeItemTemplate", typeof(DataTemplate), typeof(ListPicker), null);

        /// <summary>
        /// Gets or sets the header of the control.
        /// </summary>
        public object Header
        {
            get { return (object)GetValue(HeaderProperty); }
            set { SetValue(HeaderProperty, value); }
        }

        /// <summary>
        /// Identifies the Header DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty HeaderProperty =
            DependencyProperty.Register("Header", typeof(object), typeof(ListPicker), null);

        /// <summary>
        /// Gets or sets the template used to display the control's header.
        /// </summary>
        public DataTemplate HeaderTemplate
        {
            get { return (DataTemplate)GetValue(HeaderTemplateProperty); }
            set { SetValue(HeaderTemplateProperty, value); }
        }

        /// <summary>
        /// Identifies the HeaderTemplate DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty HeaderTemplateProperty =
            DependencyProperty.Register("HeaderTemplate", typeof(DataTemplate), typeof(ListPicker), null);

        /// <summary>
        /// Gets or sets the header to use when ListPickerMode is set to Full.
        /// </summary>
        public object FullModeHeader
        {
            get { return (object)GetValue(FullModeHeaderProperty); }
            set { SetValue(FullModeHeaderProperty, value); }
        }

        /// <summary>
        /// Identifies the FullModeHeader DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty FullModeHeaderProperty =
            DependencyProperty.Register("FullModeHeader", typeof(object), typeof(ListPicker), null);

        /// <summary>
        /// Gets the maximum number of items for which Expanded mode will be used, 5.
        /// </summary>
        public int ItemCountThreshold
        {
            get { return (int)GetValue(ItemCountThresholdProperty); }
            private set { SetValue(ItemCountThresholdProperty, value); }
        }

        /// <summary>
        /// Identifies the ItemCountThreshold DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ItemCountThresholdProperty =
            DependencyProperty.Register("ItemCountThreshold", typeof(int), typeof(ListPicker), new PropertyMetadata(5, OnItemCountThresholdChanged));

        private static void OnItemCountThresholdChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ListPicker)o).OnItemCountThresholdChanged(/*(int)e.OldValue,*/ (int)e.NewValue);
        }

        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Following DependencyProperty property changed handler convention.")]
        [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "Providing the DependencyProperty name is preferred here.")]
        private void OnItemCountThresholdChanged(/*int oldValue,*/ int newValue)
        {
            if (newValue < 0)
            {
                throw new ArgumentOutOfRangeException("ItemCountThreshold");
            }
        }

        /// <summary>
        /// Gets or sets the Uri to use for loading the ListPickerPage instance when the control is tapped.
        /// </summary>
        public Uri PickerPageUri
        {
            get { return (Uri)GetValue(PickerPageUriProperty); }
            set { SetValue(PickerPageUriProperty, value); }
        }

        /// <summary>
        /// Identifies the PickerPageUri DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty PickerPageUriProperty = DependencyProperty.Register(
            "PickerPageUri", typeof(Uri), typeof(ListPicker), null);

        /// <summary>
        /// Gets or sets how the list picker expands when tapped.
        /// This property has an effect only when SelectionMode is Single.
        /// When SelectionMode is Multiple, the ExpansionMode will be treated as FullScreenOnly.
        /// ExpansionAllowed will only expand when the number of items is less than or equalt to ItemCountThreshold
        /// Single by default.
        /// </summary>
        public ExpansionMode ExpansionMode
        {
            get { return (ExpansionMode)GetValue(ExpansionModeProperty); }
            set { SetValue(ExpansionModeProperty, value); }
        }

        /// <summary>
        /// Identifies the ExpansionMode DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ExpansionModeProperty = DependencyProperty.Register(
            "ExpansionMode",
            typeof(ExpansionMode),
            typeof(ListPicker),
            new PropertyMetadata(ExpansionMode.ExpansionAllowed, null)
            );

        /// <summary>
        /// Gets or sets the SelectionMode. Extended is treated as Multiple.
        /// Single by default.
        /// </summary>
        public SelectionMode SelectionMode
        {
            get { return (SelectionMode)GetValue(SelectionModeProperty); }
            set { SetValue(SelectionModeProperty, value); }
        }

        /// <summary>
        /// Identifies the SelectionMode DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty SelectionModeProperty = DependencyProperty.Register(
            "SelectionMode",
            typeof(SelectionMode),
            typeof(ListPicker),
            new PropertyMetadata(SelectionMode.Single, OnSelectionModeChanged)
            );

        private static void OnSelectionModeChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ListPicker)o).OnSelectionModeChanged((SelectionMode)e.NewValue);
        }

        private void OnSelectionModeChanged(SelectionMode newValue)
        {
            // Show/Hide the multiple selection mode summary text block or the items presenter depending on which selection mode chosen
            if (newValue == SelectionMode.Multiple || newValue == SelectionMode.Extended)
            {
                if (_multipleSelectionModeSummary != null && _itemsPresenterHostPart != null)
                {
                    _multipleSelectionModeSummary.Visibility = Visibility.Visible;
                    _itemsPresenterHostPart.Visibility = Visibility.Collapsed;
                }

            }
            else
            {
                if (_multipleSelectionModeSummary != null && _itemsPresenterHostPart != null)
                {
                    _multipleSelectionModeSummary.Visibility = Visibility.Collapsed;
                    _itemsPresenterHostPart.Visibility = Visibility.Visible;
                }
            }
        }

        /// <summary>
        /// Gets the selected items.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification="Want to allow this to be bound to.")]
        public IList SelectedItems
        {
            get { return (IList)GetValue(SelectedItemsProperty); }
            set { SetValue(SelectedItemsProperty, value); }
        }

        /// <summary>
        /// Identifies the SelectedItems DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
            "SelectedItems",
            typeof(IList),
            typeof(ListPicker),
            new PropertyMetadata(OnSelectedItemsChanged)
            );

        private static void OnSelectedItemsChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((ListPicker)o).OnSelectedItemsChanged((IList)e.OldValue, (IList)e.NewValue);
        }

        private void OnSelectedItemsChanged(IList oldValue, IList newValue)
        {
            UpdateSummary(newValue);

            // Fire SelectionChanged event
            var handler = SelectionChanged;
            if (null != handler)
            {
                IList removedItems = new List<object>();
                if (null != oldValue)
                {
                    foreach (object o in oldValue)
                    {
                        if (null == newValue || !newValue.Contains(o))
                        {
                            removedItems.Add(o);
                        }
                    }
                }
                IList addedItems = new List<object>();
                if (null != newValue)
                {
                    foreach (object o in newValue)
                    {
                        if (null == oldValue || !oldValue.Contains(o))
                        {
                            addedItems.Add(o);
                        }
                    }
                }

                handler(this, new SelectionChangedEventArgs(removedItems, addedItems));
            }
        }

        /// <summary>
        /// Initializes a new instance of the ListPicker class.
        /// </summary>
        public ListPicker()
        {
            DefaultStyleKey = typeof(ListPicker);

            Storyboard.SetTargetProperty(_heightAnimation, new PropertyPath(FrameworkElement.HeightProperty));
            Storyboard.SetTargetProperty(_translateAnimation, new PropertyPath(TranslateTransform.YProperty));

            // Would be nice if these values were customizable (ex: as DependencyProperties or in Template as VSM states)
            Duration duration = TimeSpan.FromSeconds(0.2);
            _heightAnimation.Duration = duration;
            _translateAnimation.Duration = duration;
            IEasingFunction easingFunction = new ExponentialEase { EasingMode = EasingMode.EaseInOut, Exponent = 4 };
            _heightAnimation.EasingFunction = easingFunction;
            _translateAnimation.EasingFunction = easingFunction;

            this.RegisterNotification("IsEnabled", OnIsEnabledChanged);

            Loaded += OnLoaded;
            Unloaded += OnUnloaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            UpdateVisualStates (true);
        }

        private void OnUnloaded(object sender, RoutedEventArgs e)
        {
            // Unhook any remaining event handlers
            if (null != _frame)
            {
                _frame.ManipulationStarted -= OnFrameManipulationStarted;
                _frame = null;
            }
        }

        /// <summary>
        /// Builds the visual tree for the control when a new template is applied.
        /// </summary>
        public override void OnApplyTemplate()
        {
            // Unhook from old elements
            if (null != _itemsPresenterHostParent)
            {
                _itemsPresenterHostParent.SizeChanged -= OnItemsPresenterHostParentSizeChanged;
            }
            _storyboard.Stop();

            base.OnApplyTemplate();

            // Hook up to new elements
            _itemsPresenterPart = GetTemplateChild(ItemsPresenterPartName) as ItemsPresenter;
            _itemsPresenterTranslateTransformPart = GetTemplateChild(ItemsPresenterTranslateTransformPartName) as TranslateTransform;
            _itemsPresenterHostPart = GetTemplateChild(ItemsPresenterHostPartName) as Canvas;
            _itemsPresenterHostParent = (null != _itemsPresenterHostPart) ? _itemsPresenterHostPart.Parent as FrameworkElement : null;
            _multipleSelectionModeSummary = GetTemplateChild(MultipleSelectionModeSummaryPartName) as TextBlock;
            _border = GetTemplateChild(BorderPartName) as Border;

            if (null != _itemsPresenterHostParent)
            {
                _itemsPresenterHostParent.SizeChanged += OnItemsPresenterHostParentSizeChanged;
            }
            if (null != _itemsPresenterHostPart)
            {
                Storyboard.SetTarget(_heightAnimation, _itemsPresenterHostPart);
                if (!_storyboard.Children.Contains(_heightAnimation))
                {
                    _storyboard.Children.Add(_heightAnimation);
                }
            }
            else
            {
                if (_storyboard.Children.Contains(_heightAnimation))
                {
                    _storyboard.Children.Remove(_heightAnimation);
                }
            }
            if (null != _itemsPresenterTranslateTransformPart)
            {
                Storyboard.SetTarget(_translateAnimation, _itemsPresenterTranslateTransformPart);
                if (!_storyboard.Children.Contains(_translateAnimation))
                {
                    _storyboard.Children.Add(_translateAnimation);
                }
            }
            else
            {
                if (_storyboard.Children.Contains(_translateAnimation))
                {
                    _storyboard.Children.Remove(_translateAnimation);
                }
            }

            SetBinding(ShadowItemTemplateProperty, new Binding("ItemTemplate") { Source = this });


            // Commit deferred SelectedIndex (if any)
            if (-1 != _deferredSelectedIndex)
            {
                SelectedIndex = _deferredSelectedIndex;
                _deferredSelectedIndex = -1;
            }
            if (null != _deferredSelectedItem)
            {
                SelectedItem = _deferredSelectedItem;
                _deferredSelectedItem = null;
            }

            OnSelectionModeChanged(SelectionMode);
            OnSelectedItemsChanged(SelectedItems, SelectedItems);
        }

        /// <summary>
        /// Determines if the specified item is (or is eligible to be) its own item container.
        /// </summary>
        /// <param name="item">The specified item.</param>
        /// <returns>True if the item is its own item container; otherwise, false.</returns>
        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is ListPickerItem;
        }

        /// <summary>
        /// Creates or identifies the element used to display a specified item.
        /// </summary>
        /// <returns>A container corresponding to a specified item.</returns>
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ListPickerItem();
        }

        /// <summary>
        /// Prepares the specified element to display the specified item.
        /// </summary>
        /// <param name="element">The element used to display the specified item.</param>
        /// <param name="item">The item to display.</param>
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);

            // Hook up to interesting events
            ContentControl container = (ContentControl)element;
            container.Tap += OnContainerTap;
            container.SizeChanged += OnListPickerItemSizeChanged;

            // Size for selected item if it's this one
            if (object.Equals(item, SelectedItem))
            {
                SizeForAppropriateView(false);
            }
        }

        /// <summary>
        /// Undoes the effects of the PrepareContainerForItemOverride method.
        /// </summary>
        /// <param name="element">The container element.</param>
        /// <param name="item">The item.</param>
        protected override void ClearContainerForItemOverride(DependencyObject element, object item)
        {
            base.ClearContainerForItemOverride(element, item);

            // Unhook from events
            ContentControl container = (ContentControl)element;
            container.Tap -= OnContainerTap;
            container.SizeChanged -= OnListPickerItemSizeChanged;
        }

        /// <summary>
        /// Provides handling for the ItemContainerGenerator.ItemsChanged event.
        /// </summary>
        /// <param name="e">A NotifyCollectionChangedEventArgs that contains the event data.</param>
        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);

            if ((0 < Items.Count) && (null == SelectedItem))
            {
                // Nothing selected (and no pending Binding); select the first item
                if ((null == GetBindingExpression(SelectedIndexProperty)) &&
                    (null == GetBindingExpression(SelectedItemProperty)))
                {
                    SelectedIndex = 0;
                }
            }
            else if (0 == Items.Count)
            {
                // No items; select nothing
                SelectedIndex = -1;
                ListPickerMode = ListPickerMode.Normal;
            }
            else if (Items.Count <= SelectedIndex)
            {
                // Selected item no longer present; select the last item
                SelectedIndex = Items.Count - 1;
            }
            else
            {
                // Re-synchronize SelectedIndex with SelectedItem if necessary
                if (!object.Equals(Items[SelectedIndex], SelectedItem))
                {
                    int selectedItemIndex = Items.IndexOf(SelectedItem);
                    if (-1 == selectedItemIndex)
                    {
                        SelectedItem = Items[0];
                    }
                    else
                    {
                        SelectedIndex = selectedItemIndex;
                    }
                }
            }

            // Translate it into view once layout has been updated for the added/removed item(s)
            Dispatcher.BeginInvoke(() => SizeForAppropriateView(false));
        }

        private bool IsValidManipulation(object OriginalSource, Point p)
        {
            DependencyObject element = OriginalSource as DependencyObject;

            while (null != element)
            {
                if (_itemsPresenterHostPart == element || _multipleSelectionModeSummary == element || _border == element)
                {
                    double Padding = 11.0;
                    return (p.X > 0 && p.Y > 0 - Padding && p.X < _border.RenderSize.Width && p.Y < _border.RenderSize.Height + Padding);
                }

                element = VisualTreeHelper.GetParent(element);
            }
            return false;
        }

        /// <summary>
        /// Handles the tap event.
        /// </summary>
        /// <param name="e">Event args</param>
        protected override void OnTap(System.Windows.Input.GestureEventArgs e)
        {
            if (null == e)
            {
                throw new ArgumentNullException("e");
            }

            if (ListPickerMode == ListPickerMode.Normal)
            {
                if (!IsEnabled)
                {
                    e.Handled = true;
                    return;
                }

                Point p = e.GetPosition((UIElement)e.OriginalSource);
                if (IsValidManipulation(e.OriginalSource, p))
                {
                    if (Open())
                    {
                        e.Handled = true;
                    }
                }
            }
        }
        /// <summary>
        /// Called when the ManipulationStarted event occurs.
        /// </summary>
        /// <param name="e">Event data for the event.</param>
        protected override void OnManipulationStarted(ManipulationStartedEventArgs e)
        {
            if (null == e)
            {
                throw new ArgumentNullException("e");
            }

            base.OnManipulationStarted(e);

            if (ListPickerMode == ListPickerMode.Normal)
            {
                if (!IsEnabled)
                {
                    e.Complete();
                    return;
                }

                Point p = e.ManipulationOrigin;

                if (e.OriginalSource != e.ManipulationContainer)
                {
                    p = e.ManipulationContainer.TransformToVisual((UIElement)e.OriginalSource).Transform(p);
                }

                if (IsValidManipulation(e.OriginalSource, p))
                {
                    IsHighlighted = true;
                }
            }
        }

        /// <summary>
        /// Called when the ManipulationDelta event occurs.
        /// </summary>
        /// <param name="e">Event data for the event.</param>
        protected override void OnManipulationDelta(ManipulationDeltaEventArgs e)
        {
            if (null == e)
            {
                throw new ArgumentNullException("e");
            }

            base.OnManipulationDelta(e);

            if (ListPickerMode == ListPickerMode.Normal)
            {
                if (!IsEnabled)
                {
                    e.Complete();
                    return;
                }

                Point p = e.ManipulationOrigin;

                if (e.OriginalSource != e.ManipulationContainer)
                {
                    p = e.ManipulationContainer.TransformToVisual((UIElement)e.OriginalSource).Transform(p);
                }

                if (!IsValidManipulation(e.OriginalSource, p))
                {
                    IsHighlighted = false;
                    e.Complete();
                }
            }
        }

        /// <summary>
        /// Called when the ManipulationCompleted event occurs.
        /// </summary>
        /// <param name="e">Event data for the event.</param>
        protected override void OnManipulationCompleted(ManipulationCompletedEventArgs e)
        {
            if (null == e)
            {
                throw new ArgumentNullException("e");
            }

            base.OnManipulationCompleted(e);

            if (!IsEnabled)
            {
                return;
            }

            if (ListPickerMode == ListPickerMode.Normal)
            {
                // Style box to look unselected
                IsHighlighted = false;
            }
        }

        /// <summary>
        /// Opens the picker for selection either into Expanded or Full mode depending on the picker's state.
        /// </summary>
        /// <returns>Whether the picker was succesfully opened.</returns>
        public bool Open()
        {
            if (SelectionMode == SelectionMode.Single)
            {
                // On interaction, switch to Expanded/Full mode
                if ((ListPickerMode.Normal == ListPickerMode))
                {
                    if (ExpansionMode == ExpansionMode.ExpansionAllowed && Items.Count <= ItemCountThreshold)
                    {
                        ListPickerMode = ListPickerMode.Expanded;
                    }
                    else
                    {
                        ListPickerMode = ListPickerMode.Full;
                    }
                    return true;
                }
            }
            else
            {
                ListPickerMode = ListPickerMode.Full;
                return true;
            }

            return false;
        }

        private void OnItemsPresenterHostParentSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (null != _itemsPresenterPart && null != _itemsPresenterHostPart && (e.NewSize.Width != e.PreviousSize.Width || e.NewSize.Width == 0))
            {
                // The control size has changed and we need to update the items presenter's size as well
                // as its host's size (the canvas).
                UpdateItemsPresenterWidth(e.NewSize.Width);
            }

            // Update clip to show only the selected item in Normal mode
            _itemsPresenterHostParent.Clip = new RectangleGeometry { Rect = new Rect(new Point(), e.NewSize) };
        }

        private void UpdateItemsPresenterWidth(double availableWidth)
        {
            // First, we clear everthing and we measure the items presenter desired size.
            _itemsPresenterPart.Width = _itemsPresenterHostPart.Width = double.NaN;
            _itemsPresenterPart.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

            // We set the host's width to the presenter's desired width only if no explicit width is set and
            // the horizontal alignment isn't stretch (when the horizontal alignment is stretch, the canvas is
            // automatically stretched).
            if (double.IsNaN(Width) && HorizontalAlignment != HorizontalAlignment.Stretch)
            {
                _itemsPresenterHostPart.Width = _itemsPresenterPart.DesiredSize.Width;
            }

            if (availableWidth > _itemsPresenterPart.DesiredSize.Width)
                _itemsPresenterPart.Width = availableWidth;
        }

        private void OnListPickerItemSizeChanged(object sender, SizeChangedEventArgs e)
        {
            // Update size accordingly
            ContentControl container = (ContentControl)sender;
            if (object.Equals(ItemContainerGenerator.ItemFromContainer(container), SelectedItem))
            {
                SizeForAppropriateView(false);
            }

            // Updates the host's width to reflect the items presenter desired width.
            if (double.IsNaN(Width) && HorizontalAlignment != HorizontalAlignment.Stretch)
            {
                _itemsPresenterHostPart.Width = _itemsPresenterPart.DesiredSize.Width;
            }
        }

        private void OnPageBackKeyPress(object sender, CancelEventArgs e)
        {
            // Revert to Normal mode
            ListPickerMode = ListPickerMode.Normal;
            e.Cancel = true;
        }

        private void SizeForAppropriateView(bool animate)
        {
            switch (ListPickerMode)
            {
                case ListPickerMode.Normal:
                    SizeForNormalMode(animate);
                    break;
                case ListPickerMode.Expanded:
                    SizeForExpandedMode();
                    break;
                case ListPickerMode.Full:
                    // Nothing to do
                    return;
            }

            // Play the height/translation animations
            _storyboard.Begin();
            if (!animate)
            {
                _storyboard.SkipToFill();
            }
        }

        private void SizeForNormalMode(bool animate)
        {
            ContentControl container = (ContentControl)ItemContainerGenerator.ContainerFromItem(SelectedItem);
            if (null != container)
            {
                // Set height/translation to show just the selected item
                if (0 < container.ActualHeight)
                {
                    SetContentHeight(container.ActualHeight + container.Margin.Top + container.Margin.Bottom - (NormalModeOffset * 2));
                }
                if (null != _itemsPresenterTranslateTransformPart)
                {
                    if (!animate)
                    {
                        _itemsPresenterTranslateTransformPart.Y = -NormalModeOffset;
                    }
                    _translateAnimation.To = container.Margin.Top - LayoutInformation.GetLayoutSlot(container).Top - NormalModeOffset;
                    _translateAnimation.From = animate ? null : _translateAnimation.To;
                }
            }
            else
            {
                // Resize to minimum height
                SetContentHeight(0);
            }

            // Clear highlight of previously selected container
            ListPickerItem oldContainer = (ListPickerItem)ItemContainerGenerator.ContainerFromIndex(SelectedIndex);
            if (null != oldContainer)
            {
                oldContainer.IsSelected = false;
            }
        }

        private void SizeForExpandedMode()
        {
            // Set height and align first element at top
            if (null != _itemsPresenterPart)
            {
                SetContentHeight(_itemsPresenterPart.ActualHeight);
            }
            if (null != _itemsPresenterTranslateTransformPart)
            {
                _translateAnimation.To = 0;
            }

            // Highlight selected container
            ListPickerItem container = (ListPickerItem)ItemContainerGenerator.ContainerFromIndex(SelectedIndex);
            if (null != container)
            {
                container.IsSelected = true;
            }
        }

        private void SetContentHeight(double height)
        {
            if ((null != _itemsPresenterHostPart) && !double.IsNaN(height))
            {
                double canvasHeight = _itemsPresenterHostPart.Height;
                _heightAnimation.From = double.IsNaN(canvasHeight) ? height : canvasHeight;
                _heightAnimation.To = height;
            }
        }

        private void OnFrameManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            if (ListPickerMode.Expanded == ListPickerMode)
            {
                // Manipulation outside an Expanded ListPicker reverts to Normal mode
                DependencyObject element = e.OriginalSource as DependencyObject;
                DependencyObject cancelElement = (DependencyObject)_itemsPresenterHostPart ?? (DependencyObject)this;
                while (null != element)
                {
                    if (cancelElement == element)
                    {
                        return;
                    }
                    element = VisualTreeHelper.GetParent(element);
                }
                ListPickerMode = ListPickerMode.Normal;
            }
        }

        private void OnContainerTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (ListPickerMode.Expanded == ListPickerMode)
            {
                // Manipulation of a container selects the item and reverts to Normal mode
                ContentControl container = (ContentControl)sender;
                SelectedItem = ItemContainerGenerator.ItemFromContainer(container);
                ListPickerMode = ListPickerMode.Normal;
                e.Handled = true;
            }
        }

        private void UpdateVisualStates(bool useTransitions)
        {
            if (!IsEnabled)
            {
                VisualStateManager.GoToState(this, PickerStatesDisabledStateName, useTransitions);
            }
            else if (IsHighlighted)
            {
                VisualStateManager.GoToState(this, PickerStatesHighlightedStateName, useTransitions);
            }
            else
            {
                VisualStateManager.GoToState(this, PickerStatesNormalStateName, useTransitions);
            }
        }

        /// <summary>
        /// Updates the summary of the selected items to be displayed in the ListPicker.
        /// </summary>
        /// <param name="newValue">The list selected items</param>
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Windows.Controls.TextBlock.set_Text(System.String)", Justification = "By design.")]
        private void UpdateSummary(IList newValue)
        {
            const string space = " ";
            string summary = null;

            if (null != SummaryForSelectedItemsDelegate)
            {
                // Ask the delegate to sumarize the selected items.
                summary = SummaryForSelectedItemsDelegate(newValue);
            }

            if (summary == null)
            {
                // No summary was provided, so by default, show only the first item in the selection list.
                if (null == newValue || newValue.Count == 0)
                {
                    // In the case that there were no selected items, show the empty string.
                    summary = space;
                }
                else
                {
                    summary = newValue[0].ToString();
                }
            }

            // The display does not size correctly if the empty string is used.
            if (String.IsNullOrEmpty(summary))
            {
                summary = space;
            }

            if (null != _multipleSelectionModeSummary)
            {
                _multipleSelectionModeSummary.Text = summary;
            }
        }

        private void OpenPickerPage()
        {
            if (null == PickerPageUri)
            {
                throw new ArgumentException("PickerPageUri");
            }

            if (null == _frame)
            {
                // Hook up to necessary events and navigate
                _frame = Application.Current.RootVisual as PhoneApplicationFrame;
                if (null != _frame)
                {
                    _frameContentWhenOpened = _frame.Content;

                    // Save and clear host page transitions for the upcoming "popup" navigation
                    UIElement frameContentWhenOpenedAsUIElement = _frameContentWhenOpened as UIElement;

                    if (null != frameContentWhenOpenedAsUIElement)
                    {
                        _savedNavigationInTransition = TransitionService.GetNavigationInTransition(frameContentWhenOpenedAsUIElement);
                        TransitionService.SetNavigationInTransition(frameContentWhenOpenedAsUIElement, null);
                        _savedNavigationOutTransition = TransitionService.GetNavigationOutTransition(frameContentWhenOpenedAsUIElement);
                        TransitionService.SetNavigationOutTransition(frameContentWhenOpenedAsUIElement, null);

                    }

                    _frame.Navigated += OnFrameNavigated;
                    _frame.NavigationStopped += OnFrameNavigationStoppedOrFailed;
                    _frame.NavigationFailed += OnFrameNavigationStoppedOrFailed;

                    _hasPickerPageOpen = true;

                    _frame.Navigate(PickerPageUri);
                }
            }
        }

        private void ClosePickerPage()
        {
            if (null == _frame)
            {
                // Unhook from events
                _frame = Application.Current.RootVisual as PhoneApplicationFrame;
                if (null != _frame)
                {
                    _frame.Navigated -= OnFrameNavigated;
                    _frame.NavigationStopped -= OnFrameNavigationStoppedOrFailed;
                    _frame.NavigationFailed -= OnFrameNavigationStoppedOrFailed;

                    // Restore host page transitions for the completed "popup" navigation
                    UIElement frameContentWhenOpenedAsUIElement = _frameContentWhenOpened as UIElement;

                    if (null != frameContentWhenOpenedAsUIElement)
                    {
                        TransitionService.SetNavigationInTransition(frameContentWhenOpenedAsUIElement, _savedNavigationInTransition);
                        _savedNavigationInTransition = null;
                        TransitionService.SetNavigationOutTransition(frameContentWhenOpenedAsUIElement, _savedNavigationOutTransition);
                        _savedNavigationOutTransition = null;
                    }

                    _frame = null;
                    _frameContentWhenOpened = null;
                }
            }

            // Commit the value if available
            if (null != _listPickerPage)
            {
                if (SelectionMode == SelectionMode.Single && null != _listPickerPage.SelectedItem)
                {
                    SelectedItem = _listPickerPage.SelectedItem;
                }
                else if ((SelectionMode == SelectionMode.Multiple || SelectionMode == SelectionMode.Extended) && null != _listPickerPage.SelectedItems)
                {
                    SelectedItems = _listPickerPage.SelectedItems;
                }
                _listPickerPage = null;
            }
        }

        private void OnFrameNavigated(object sender, NavigationEventArgs e)
        {
            if (e.Content == _frameContentWhenOpened)
            {
                // Navigation to original page; close the picker page
                ListPickerMode = ListPickerMode.Normal;
            }
            else if (null == _listPickerPage && _hasPickerPageOpen)
            {
                _hasPickerPageOpen = false;
                _listPickerPage = e.Content as ListPickerPage;
                if (null != _listPickerPage)
                {
                    // Sets the flow direction.
                    _listPickerPage.FlowDirection = this.FlowDirection;

                    // Set up the list picker page with the necesarry fields.
                    if (null != FullModeHeader)
                    {
                        _listPickerPage.HeaderText = (string)FullModeHeader;
                    }
                    else
                    {
                        _listPickerPage.HeaderText = (string) Header;
                    }

                    _listPickerPage.FullModeItemTemplate = FullModeItemTemplate;

                    _listPickerPage.Items.Clear();
                    if (null != Items)
                    {
                        foreach (var element in Items)
                        {
                            _listPickerPage.Items.Add(element);
                        }
                    }

                    _listPickerPage.SelectionMode = SelectionMode;

                    if (SelectionMode == SelectionMode.Single)
                    {
                        _listPickerPage.SelectedItem = SelectedItem;
                    }
                    else
                    {
                        _listPickerPage.SelectedItems.Clear();
                        if (null != SelectedItems)
                        {
                            foreach (var element in SelectedItems)
                            {
                                _listPickerPage.SelectedItems.Add(element);
                            }
                        }
                    }
                }
            }
        }

        private void OnFrameNavigationStoppedOrFailed(object sender, EventArgs e)
        {
            // Abort
            ListPickerMode = ListPickerMode.Normal;
        }
    }
}
Back to Top