-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathListViewPage.xaml.cs
More file actions
476 lines (402 loc) · 18.6 KB
/
Copy pathListViewPage.xaml.cs
File metadata and controls
476 lines (402 loc) · 18.6 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Navigation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using WinUIGallery.Helpers;
using WinUIGallery.Pages;
namespace WinUIGallery.ControlPages;
public sealed partial class ListViewPage : ItemsPageBase
{
ObservableCollection<Contact> contacts1 = new ObservableCollection<Contact>();
ObservableCollection<Contact> contacts2 = new ObservableCollection<Contact>();
ObservableCollection<Contact> contacts3 = new ObservableCollection<Contact>();
ObservableCollection<Contact> contacts3Filtered = new ObservableCollection<Contact>();
ObservableCollection<Contact> contacts4ContextMenu = new ObservableCollection<Contact>();
ObservableCollection<string> contacts5 = new ObservableCollection<string>();
ObservableCollection<string> contacts6 = new ObservableCollection<string>();
private string _persistedPosition = string.Empty;
ItemsStackPanel? stackPanelObj;
int messageNumber;
public ListViewPage()
{
this.InitializeComponent();
// Add first item to inverted list so it's not empty
AddItemToEnd();
BaseExample.Loaded += BaseExample_Loaded;
}
private void BaseExample_Loaded(object sender, RoutedEventArgs e)
{
// Set focus so the first item of the listview has focus
// instead of some item which is not visible on page load
BaseExample.Focus(FocusState.Programmatic);
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
Items = ControlInfoDataSource.Instance.Groups.Take(3).SelectMany(g => g.Items).ToList();
BaseExample.ItemsSource = await Contact.GetContactsAsync();
Control2.ItemsSource = await Contact.GetContactsAsync();
contacts1 = await Contact.GetContactsAsync();
DragDropListView.ItemsSource = contacts1;
contacts2.Add(new Contact("John", "Doe", "ABC Printers"));
contacts2.Add(new Contact("Jane", "Doe", "XYZ Refrigerators"));
contacts2.Add(new Contact("Santa", "Claus", "North Pole Toy Factory Inc."));
DragDropListView2.ItemsSource = contacts2;
Control4.ItemsSource = WinUIGallery.ControlPages.CustomDataObject.GetDataObjects();
ContactsCVS.Source = await Contact.GetContactsGroupedAsync();
// Initialize list of contacts to be filtered
contacts3 = await Contact.GetContactsAsync();
contacts3Filtered = new ObservableCollection<Contact>(contacts3);
// Initializze list of contacts for context menu sample
contacts4ContextMenu = await Contact.GetContactsAsync();
ContextMenuList.ItemsSource = contacts4ContextMenu;
// Populate ListViews for the RestoreScrollPosition and ScrollIntoView samples.
// Pre-format each entry with its index so the position in the list is easy to track.
var baseContacts = await Contact.GetContactsAsync();
contacts5 = new ObservableCollection<string>(
baseContacts.Select((c, i) => $"{i + 1}. {c.Name}"));
// ScrollIntoView is more interesting with a long list, so seed multiple copies.
var manyContacts = new List<string>();
int n = 1;
for (int i = 0; i < 10; i++)
{
foreach (var c in baseContacts)
{
manyContacts.Add($"{n++}. {c.Name}");
}
}
contacts6 = new ObservableCollection<string>(manyContacts);
RestoreScrollListView.ItemsSource = contacts5;
ScrollIntoViewListView.ItemsSource = contacts6;
FilteredListView.ItemsSource = contacts3Filtered;
}
//===================================================================================================================
// Selection Modes Example
//===================================================================================================================
private void SelectionModeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (Control2 != null)
{
string? selectionMode = e.AddedItems[0].ToString();
switch (selectionMode)
{
case "None":
Control2.SelectionMode = ListViewSelectionMode.None;
break;
case "Single":
Control2.SelectionMode = ListViewSelectionMode.Single;
break;
case "Multiple":
Control2.SelectionMode = ListViewSelectionMode.Multiple;
break;
case "Extended":
Control2.SelectionMode = ListViewSelectionMode.Extended;
break;
}
}
}
//===================================================================================================================
// Drag/Drop Example
//===================================================================================================================
private void ListView_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
var contactsToMove = e.Items.OfType<Contact>().ToList();
e.Data.Properties["contacts"] = contactsToMove;
e.Data.RequestedOperation = DataPackageOperation.Move;
}
private void Target_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Move;
}
private void Source_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Move;
}
private void ListView_Drop(object sender, DragEventArgs e)
{
ListView target = (ListView)sender;
if (e.DataView.Properties["contacts"] != null)
{
DragOperationDeferral def = e.GetDeferral();
var contactsToMove = (List<Contact>)e.DataView.Properties["contacts"];
foreach (var contactToMove in contactsToMove)
{
// Find the insertion index:
Windows.Foundation.Point pos = e.GetPosition(target.ItemsPanelRoot);
// If the target ListView has items in it, use the height of the first item
// to find the insertion index.
int index = 0;
if (target.Items.Count != 0)
{
// Get a reference to the first item in the ListView
ListViewItem sampleItem = (ListViewItem)target.ContainerFromIndex(0);
// Adjust itemHeight for margins
double itemHeight = sampleItem.ActualHeight + sampleItem.Margin.Top + sampleItem.Margin.Bottom;
// Find index based on dividing number of items by height of each item
index = Math.Min(target.Items.Count - 1, (int)(pos.Y / itemHeight));
// Find the item being dropped on top of.
ListViewItem targetItem = (ListViewItem)target.ContainerFromIndex(index);
// If the drop position is more than half-way down the item being dropped on
// top of, increment the insertion index so the dropped item is inserted
// below instead of above the item being dropped on top of.
Windows.Foundation.Point positionInItem = e.GetPosition(targetItem);
if (positionInItem.Y > itemHeight / 2)
{
index++;
}
// Don't go out of bounds
index = Math.Min(target.Items.Count, index);
}
// Only other case is if the target ListView has no items (the dropped item will be
// the first). In that case, the insertion index will remain zero.
// Find correct source list
if (target.Name == "DragDropListView")
{
// Find the ItemsSource for the target ListView and insert
contacts1.Insert(index, contactToMove);
//Go through source list and remove the items that are being moved
foreach (Contact contact in DragDropListView2.Items)
{
if (contact.FirstName == contactToMove.FirstName && contact.LastName == contactToMove.LastName && contact.Company == contactToMove.Company)
{
contacts2.Remove(contact);
break;
}
}
}
else if (target.Name == "DragDropListView2")
{
contacts2.Insert(index, contactToMove);
foreach (Contact contact in DragDropListView.Items)
{
if (contact.FirstName == contactToMove.FirstName && contact.LastName == contactToMove.LastName && contact.Company == contactToMove.Company)
{
contacts1.Remove(contact);
break;
}
}
}
}
e.AcceptedOperation = DataPackageOperation.Move;
def.Complete();
}
}
private void Target_DragEnter(object sender, DragEventArgs e)
{
// We don't want to show the Move icon
e.DragUIOverride.IsGlyphVisible = false;
}
//===================================================================================================================
// Grouped Headers Example
//===================================================================================================================
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
{
if (StickySwitch != null && stackPanelObj is not null)
{
if (StickySwitch.IsOn == true)
{
stackPanelObj.AreStickyGroupHeadersEnabled = true;
}
else
{
stackPanelObj.AreStickyGroupHeadersEnabled = false;
}
}
}
private void StackPanel_loaded(object sender, RoutedEventArgs e)
{
stackPanelObj = sender as ItemsStackPanel;
}
//===================================================================================================================
// Filtered List Example
//===================================================================================================================
private void Remove_NonMatching(IEnumerable<Contact> filteredData)
{
for (int i = contacts3Filtered.Count - 1; i >= 0; i--)
{
var item = contacts3Filtered[i];
// If contact is not in the filtered argument list, remove it from the ListView's source.
if (!filteredData.Contains(item))
{
contacts3Filtered.Remove(item);
}
}
}
private void AddBack_Contacts(IEnumerable<Contact> filteredData)
// When a user hits backspace, more contacts may need to be added back into the list
{
foreach (var item in filteredData)
{
// If item in filtered list is not currently in ListView's source collection, add it back in
if (!contacts3Filtered.Contains(item))
{
contacts3Filtered.Add(item);
}
}
}
private void OnFilterChanged(object sender, TextChangedEventArgs args)
{
// Linq query that selects only items that return True after being passed through Filter function
var filtered = contacts3.Where(contact => Filter(contact));
Remove_NonMatching(filtered);
AddBack_Contacts(filtered);
UIHelper.AnnounceActionForAccessibility(FilteredListView, $"Found {filtered.Count()} contacts", "ContactListViewFilteredActivityId");
}
private bool Filter(Contact contact)
{
// When the text in any filter is changed, contact list is ran through all three filters to make sure
// they can properly interact with each other (i.e. they can all be applied at the same time).
return contact.FirstName.Contains(FilterByFirstName.Text, StringComparison.InvariantCultureIgnoreCase) &&
contact.LastName.Contains(FilterByLastName.Text, StringComparison.InvariantCultureIgnoreCase) &&
contact.Company.Contains(FilterByCompany.Text, StringComparison.InvariantCultureIgnoreCase);
}
//===================================================================================================================
// Inverted List Example
//===================================================================================================================
private void AddItemToEnd()
{
InvertedListView.Items.Add(
new Message("Message " + ++messageNumber, DateTime.Now, HorizontalAlignment.Right)
);
}
private void MessageReceived(object sender, RoutedEventArgs e)
{
InvertedListView.Items.Add(
new Message("Message " + ++messageNumber, DateTime.Now, HorizontalAlignment.Left)
);
}
//===================================================================================================================
// ListView with Images Sample
//===================================================================================================================
private void TextBlock_IsTextTrimmedChanged(TextBlock sender, IsTextTrimmedChangedEventArgs args)
{
var textBlock = sender as TextBlock;
var text = textBlock.IsTextTrimmed ? textBlock.Text : string.Empty;
ToolTipService.SetToolTip(textBlock, text);
}
//===================================================================================================================
// ListView with context menu
//===================================================================================================================
private void ContactDeleteMenuItem_Click(object sender, RoutedEventArgs e)
{
if ((sender as FrameworkElement)?.DataContext is not Contact contact)
{
return;
}
contacts4ContextMenu.Remove(contact);
}
//===================================================================================================================
// Save / restore scroll position sample
//===================================================================================================================
private void SavePositionButton_Click(object sender, RoutedEventArgs e)
{
// GetRelativeScrollPosition returns an opaque string identifying the item at the
// top of the viewport plus its pixel offset. Store it for later restoration.
_persistedPosition = ListViewPersistenceHelper.GetRelativeScrollPosition(
RestoreScrollListView,
item => item as string ?? string.Empty);
SavedPositionTextBlock.Text = $"Saved position: {_persistedPosition}";
RestorePositionButton.IsEnabled = true;
}
private async void RestorePositionButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(_persistedPosition))
{
return;
}
// SetRelativeScrollPositionAsync scrolls the ListView back to the item identified
// by the saved string. The callback resolves a key back to its data item.
await ListViewPersistenceHelper.SetRelativeScrollPositionAsync(
RestoreScrollListView,
_persistedPosition,
key => Task.FromResult<object?>(contacts5.FirstOrDefault(c => c == key))!.AsAsyncOperation()!);
}
//===================================================================================================================
// ScrollIntoView sample
//===================================================================================================================
private void ScrollIntoViewButton_Click(object sender, RoutedEventArgs e)
{
int index = (int)ScrollIndexNumberBox.Value;
if (index < 0 || index >= ScrollIntoViewListView.Items.Count)
{
return;
}
var alignment = ScrollAlignmentComboBox.SelectedIndex == 1
? ScrollIntoViewAlignment.Leading
: ScrollIntoViewAlignment.Default;
ScrollIntoViewListView.ScrollIntoView(ScrollIntoViewListView.Items[index], alignment);
}
}
public class Message
{
public string MsgText { get; private set; }
public DateTime MsgDateTime { get; private set; }
public HorizontalAlignment MsgAlignment { get; set; }
public Message(string text, DateTime dateTime, HorizontalAlignment align)
{
MsgText = text;
MsgDateTime = dateTime;
MsgAlignment = align;
}
public override string ToString()
{
return MsgDateTime.ToString() + " " + MsgText;
}
}
public class Contact
{
#region Properties
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string Company { get; private set; }
public string Name => FirstName + " " + LastName;
#endregion
public Contact(string firstName, string lastName, string company)
{
FirstName = firstName;
LastName = lastName;
Company = company;
}
#region Public Methods
public async static Task<ObservableCollection<Contact>> GetContactsAsync()
{
IList<string> lines = await FileLoader.LoadLines("Assets/SampleMedia/Contacts.txt");
ObservableCollection<Contact> contacts = new ObservableCollection<Contact>();
for (int i = 0; i < lines.Count - 2; i += 3)
{
contacts.Add(new Contact(lines[i], lines[i + 1], lines[i + 2]));
}
return contacts;
}
public static async Task<ObservableCollection<GroupInfoList>> GetContactsGroupedAsync()
{
var query = from item in await GetContactsAsync()
group item by item.LastName.Substring(0, 1).ToUpper() into g
orderby g.Key
select new GroupInfoList(g) { Key = g.Key };
return new ObservableCollection<GroupInfoList>(query);
}
public override string ToString()
{
return $"{Name}, {Company}";
}
#endregion
}
public partial class GroupInfoList : List<object>
{
public GroupInfoList(IEnumerable<object> items) : base(items)
{
}
public object? Key { get; set; }
public override string ToString()
{
return "Group " + Key?.ToString();
}
}