-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
MainWindowViewModel.cs
599 lines (467 loc) · 24.5 KB
/
MainWindowViewModel.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using MetroDemo.Models;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MetroDemo.Core;
using MetroDemo.ExampleViews;
using NHotkey;
using NHotkey.Wpf;
using System.Collections.ObjectModel;
using System.Windows.Data;
using ControlzEx.Theming;
namespace MetroDemo
{
public class AccentColorMenuData
{
public string? Name { get; set; }
public Brush? BorderColorBrush { get; set; }
public Brush? ColorBrush { get; set; }
public AccentColorMenuData()
{
this.ChangeAccentCommand = new SimpleCommand<string?>(o => true, this.DoChangeTheme);
}
public ICommand ChangeAccentCommand { get; }
protected virtual void DoChangeTheme(string? name)
{
if (name is not null)
{
ThemeManager.Current.ChangeThemeColorScheme(Application.Current, name);
}
}
}
public class AppThemeMenuData : AccentColorMenuData
{
protected override void DoChangeTheme(string? name)
{
if (name is not null)
{
ThemeManager.Current.ChangeThemeBaseColor(Application.Current, name);
}
}
}
public class MainWindowViewModel : ViewModelBase, IDataErrorInfo, IDisposable
{
private readonly IDialogCoordinator _dialogCoordinator;
int? _integerGreater10Property = 2;
private bool _animateOnPositionChange = true;
public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
{
this.Title = "Flyout Binding Test";
this._dialogCoordinator = dialogCoordinator;
SampleData.Seed();
// create accent color menu items for the demo
this.AccentColors = ThemeManager.Current.Themes
.GroupBy(x => x.ColorScheme)
.OrderBy(a => a.Key)
.Select(a => new AccentColorMenuData { Name = a.Key, ColorBrush = a.First().ShowcaseBrush })
.ToList();
// create metro theme color menu items for the demo
this.AppThemes = ThemeManager.Current.Themes
.GroupBy(x => x.BaseColorScheme)
.Select(x => x.First())
.Select(a => new AppThemeMenuData { Name = a.BaseColorScheme, BorderColorBrush = a.Resources["MahApps.Brushes.ThemeForeground"] as Brush, ColorBrush = a.Resources["MahApps.Brushes.ThemeBackground"] as Brush })
.ToList();
this.Albums = new ObservableCollection<Album>(SampleData.Albums!);
var cvs = CollectionViewSource.GetDefaultView(this.Albums);
cvs.GroupDescriptions.Add(new PropertyGroupDescription("Artist"));
this.Artists = SampleData.Artists;
this.FlipViewImages = new Uri[]
{
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Home.jpg", UriKind.RelativeOrAbsolute),
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Privat.jpg", UriKind.RelativeOrAbsolute),
new Uri("pack://application:,,,/MahApps.Metro.Demo;component/Assets/Photos/Settings.jpg", UriKind.RelativeOrAbsolute)
};
this.ThemeResources = new ObservableCollection<ThemeResource>();
var view = CollectionViewSource.GetDefaultView(this.ThemeResources);
view.SortDescriptions.Add(new SortDescription(nameof(ThemeResource.Key), ListSortDirection.Ascending));
this.UpdateThemeResources();
this.CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).OrderBy(c => c.DisplayName).ToList();
try
{
if (this.HotKey is not null)
{
HotkeyManager.Current.AddOrReplace("demo", this.HotKey.Key, this.HotKey.ModifierKeys, async (sender, e) => await this.OnHotKey(sender, e));
}
}
catch (HotkeyAlreadyRegisteredException exception)
{
System.Diagnostics.Trace.TraceWarning("Uups, the hotkey {0} is already registered!", exception.Name);
}
this.EndOfScrollReachedCmdWithParameter = new SimpleCommand<object>(o => true, async x => { await this._dialogCoordinator.ShowMessageAsync(this, "End of scroll reached!", $"Parameter: {x}"); });
this.CloseCmd = new SimpleCommand<Flyout>(f => f is not null && this.CanCloseFlyout, f => f!.IsOpen = false);
this.ControlButtonCommand = new SimpleCommand<object>(
o =>
{
return o switch
{
RichTextBox richTextBox => TextBoxHelper.GetHasText(richTextBox),
TextBox textBox => TextBoxHelper.GetHasText(textBox),
_ => true
};
},
async o =>
{
switch (o)
{
case string s:
await this._dialogCoordinator.ShowMessageAsync(this, "Wow, you typed Return and got", s).ConfigureAwait(false);
break;
case RichTextBox richTextBox:
await this._dialogCoordinator.ShowMessageAsync(this, $"{o.GetType().Name} Button was clicked!", new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text).ConfigureAwait(false);
break;
case TextBox textBox:
await this._dialogCoordinator.ShowMessageAsync(this, $"{o.GetType().Name} Button was clicked!", textBox.Text).ConfigureAwait(false);
break;
case PasswordBox passwordBox:
await this._dialogCoordinator.ShowMessageAsync(this, $"{o.GetType().Name} Button was clicked!", passwordBox.Password).ConfigureAwait(false);
break;
case DatePicker datePicker:
await this._dialogCoordinator.ShowMessageAsync(this, $"{o.GetType().Name} Button was clicked!", datePicker.Text).ConfigureAwait(false);
break;
case ComboBox comboBox:
await this._dialogCoordinator.ShowMessageAsync(this, $"{o.GetType().Name} Button was clicked!", comboBox.Text).ConfigureAwait(false);
break;
case HotKeyBox hotKeyBox:
await this._dialogCoordinator.ShowMessageAsync(this, $"{o.GetType().Name} Button was clicked!", hotKeyBox.Text ?? hotKeyBox.HotKey?.ToString() ?? string.Empty).ConfigureAwait(false);
break;
case Control control:
await this._dialogCoordinator.ShowMessageAsync(this, $"{o.GetType().Name} Button was clicked!", control.ToString() ?? string.Empty).ConfigureAwait(false);
break;
}
}
);
this.ControlButtonCommandWithParameter = new SimpleCommand<object>(
o => true,
async x => { await this._dialogCoordinator.ShowMessageAsync(this, "TextBox Button with parameter was clicked!", $"Parameter: {x}"); }
);
this.SingleCloseTabCommand = new SimpleCommand<object>(
o => true,
async x => { await this._dialogCoordinator.ShowMessageAsync(this, "Closing tab!", $"You are now closing the '{x}' tab"); }
);
this.NeverCloseTabCommand = new SimpleCommand<object>(o => false);
this.ShowInputDialogCommand = new SimpleCommand<object>(
o => true,
async x => { await this._dialogCoordinator.ShowInputAsync(this, "From a VM", "This dialog was shown from a VM, without knowledge of Window").ContinueWith(t => Console.WriteLine(t.Result)); }
);
this.ShowLoginDialogCommand = new SimpleCommand<object>(
o => true,
async x => { await this._dialogCoordinator.ShowLoginAsync(this, "Login from a VM", "This login dialog was shown from a VM, so you can be all MVVM.").ContinueWith(t => Console.WriteLine(t.Result)); }
);
this.ShowMessageDialogCommand = new SimpleCommand<string>(
x => !string.IsNullOrEmpty(x),
x => PerformDialogCoordinatorAction(this.ShowMessage(x!), x == "DISPATCHER_THREAD")
);
this.ShowProgressDialogCommand = new SimpleCommand<object>(o => true, x => this.RunProgressFromVm());
this.ShowCustomDialogCommand = new SimpleCommand<object>(o => true, x => this.RunCustomFromVm());
this.ToggleIconScalingCommand = new SimpleCommand<MultiFrameImageMode?>(m => m is not null, this.ToggleIconScaling);
this.OpenFlyoutCommand = new SimpleCommand<Flyout>(f => f is not null, f => f!.SetCurrentValue(Flyout.IsOpenProperty, true));
this.CloseFlyoutCommand = new SimpleCommand<Flyout>(f => f is not null, f => f!.SetCurrentValue(Flyout.IsOpenProperty, false));
this.MoveLeftFlyoutCommand = new SimpleCommand<Flyout>(f => f is not null, f => f!.SetCurrentValue(Flyout.PositionProperty, Position.Left));
this.MoveRightFlyoutCommand = new SimpleCommand<Flyout>(f => f is not null, f => f!.SetCurrentValue(Flyout.PositionProperty, Position.Right));
this.ArtistsDropDownCommand = new SimpleCommand<object>(o => false);
this.GenreDropDownMenuItemCommand = new SimpleCommand<object>(
o => true,
async x => { await this._dialogCoordinator.ShowMessageAsync(this, "DropDownButton Menu", $"You are clicked the '{x}' menu item."); }
);
this.GenreSplitButtonItemCommand = new SimpleCommand<object>(
o => true,
async x => { await this._dialogCoordinator.ShowMessageAsync(this, "Split Button", $"The selected item is '{x}'."); }
);
this.ShowHamburgerAboutCommand = ShowAboutCommand.Command;
this.ToggleSwitchCommand = new SimpleCommand<ToggleSwitch?>(x => x is not null && this.CanUseToggleSwitch,
async x => { await this._dialogCoordinator.ShowMessageAsync(this, "ToggleSwitch", $"The ToggleSwitch is now {x!.IsOn}."); });
this.ToggleSwitchOnCommand = new SimpleCommand<MainWindowViewModel?>(x => x is not null && x.CanUseToggleSwitch,
async x => { await this._dialogCoordinator.ShowMessageAsync(this, "ToggleSwitch", "The ToggleSwitch is now On."); });
this.ToggleSwitchOffCommand = new SimpleCommand<MainWindowViewModel?>(x => x is not null && x.CanUseToggleSwitch,
async x => { await this._dialogCoordinator.ShowMessageAsync(this, "ToggleSwitch", "The ToggleSwitch is now Off."); });
var r = new Random(Environment.TickCount);
this.SelectedAnimals.Add(this.Animals.ElementAt(r.Next(0, this.Animals.Count - 1)));
this.SelectedAnimals.Add(this.Animals.ElementAt(r.Next(0, this.Animals.Count - 1)));
this.SelectedAnimals.Add(this.Animals.ElementAt(r.Next(0, this.Animals.Count - 1)));
this.MyObjectParser = new ObjectParser(this, this._dialogCoordinator);
}
public ICommand ArtistsDropDownCommand { get; }
public ICommand GenreDropDownMenuItemCommand { get; }
public ICommand GenreSplitButtonItemCommand { get; }
public ICommand ShowHamburgerAboutCommand { get; }
public ICommand OpenFlyoutCommand { get; }
public ICommand CloseFlyoutCommand { get; }
public ICommand MoveLeftFlyoutCommand { get; }
public ICommand MoveRightFlyoutCommand { get; }
public ICommand ChangeSyncModeCommand { get; } = new SimpleCommand<ThemeSyncMode?>(
x => x is not null,
x =>
{
ThemeManager.Current.ThemeSyncMode = x!.Value;
ThemeManager.Current.SyncTheme();
});
public ICommand SyncThemeNowCommand { get; } = new SimpleCommand<object>(execute: x => ThemeManager.Current.SyncTheme());
public ICommand ToggleSwitchCommand { get; }
private bool canUseToggleSwitch = true;
public bool CanUseToggleSwitch
{
get => this.canUseToggleSwitch;
set => this.Set(ref this.canUseToggleSwitch, value);
}
public ICommand ToggleSwitchOnCommand { get; }
public ICommand ToggleSwitchOffCommand { get; }
public void Dispose()
{
HotkeyManager.Current.Remove("demo");
}
private bool showTitleColumn = true;
public bool ShowTitleColumn
{
get => showTitleColumn;
set => Set(ref showTitleColumn, value);
}
public string Title { get; set; }
public int SelectedIndex { get; set; }
public ICollection<Album> Albums { get; set; }
public List<Artist>? Artists { get; set; }
private ObservableCollection<Artist>? _selectedArtists = new ObservableCollection<Artist>();
public ObservableCollection<Artist>? SelectedArtists
{
get => this._selectedArtists;
set => this.Set(ref this._selectedArtists, value);
}
public List<AccentColorMenuData> AccentColors { get; set; }
public List<AppThemeMenuData> AppThemes { get; set; }
public List<CultureInfo> CultureInfos { get; set; }
private CultureInfo? currentCulture = CultureInfo.CurrentCulture;
public CultureInfo? CurrentCulture
{
get => this.currentCulture;
set => this.Set(ref this.currentCulture, value);
}
private double numericUpDownValue = default;
public double NumericUpDownValue
{
get => this.numericUpDownValue;
set => this.Set(ref this.numericUpDownValue, value);
}
private double? nullableNumericUpDownValue = null;
public double? NullableNumericUpDownValue
{
get => this.nullableNumericUpDownValue;
set => this.Set(ref this.nullableNumericUpDownValue, value);
}
public ICommand EndOfScrollReachedCmdWithParameter { get; }
public int? IntegerGreater10Property
{
get => this._integerGreater10Property;
set => this.Set(ref this._integerGreater10Property, value);
}
private DateTime? _datePickerDate;
[Display(Prompt = "Auto resolved Watermark")]
public DateTime? DatePickerDate
{
get => this._datePickerDate;
set => this.Set(ref this._datePickerDate, value);
}
private bool _quitConfirmationEnabled;
public bool QuitConfirmationEnabled
{
get => this._quitConfirmationEnabled;
set => this.Set(ref this._quitConfirmationEnabled, value);
}
private bool canCloseFlyout = true;
public bool CanCloseFlyout
{
get => this.canCloseFlyout;
set => this.Set(ref this.canCloseFlyout, value);
}
public ICommand CloseCmd { get; }
private bool canShowHamburgerAboutCommand = true;
public bool CanShowHamburgerAboutCommand
{
get => this.canShowHamburgerAboutCommand;
set => this.Set(ref this.canShowHamburgerAboutCommand, value);
}
private bool isHamburgerMenuPaneOpen;
public bool IsHamburgerMenuPaneOpen
{
get => this.isHamburgerMenuPaneOpen;
set => this.Set(ref this.isHamburgerMenuPaneOpen, value);
}
public ICommand ControlButtonCommand { get; }
public ICommand ControlButtonCommandWithParameter { get; }
public string this[string columnName]
{
get
{
if (columnName == nameof(this.IntegerGreater10Property) && this.IntegerGreater10Property < 10)
{
return "Number is not greater than 10!";
}
if (columnName == nameof(this.DatePickerDate) && this.DatePickerDate == null)
{
return "No date given!";
}
if (columnName == nameof(this.HotKey) && this.HotKey != null && this.HotKey.Key == Key.D && this.HotKey.ModifierKeys == ModifierKeys.Shift)
{
return "SHIFT-D is not allowed";
}
if (columnName == nameof(this.TimePickerDate) && this.TimePickerDate == null)
{
return "No time given!";
}
if (columnName == nameof(this.IsToggleSwitchVisible) && !this.IsToggleSwitchVisible)
{
return "There is something hidden... \nActivate me to show it up.";
}
return null!;
}
}
[Description("Test-Property")]
public string Error => string.Empty;
private DateTime? _timePickerDate;
[Display(Prompt = "Time needed...")]
public DateTime? TimePickerDate
{
get => this._timePickerDate;
set => this.Set(ref this._timePickerDate, value);
}
public ICommand SingleCloseTabCommand { get; }
public ICommand NeverCloseTabCommand { get; }
public ICommand ShowInputDialogCommand { get; }
public ICommand ShowLoginDialogCommand { get; }
public ICommand ShowMessageDialogCommand { get; }
private Action ShowMessage(string startingThread)
{
return () =>
{
var message = $"MVVM based messages!\n\nThis dialog was created by {startingThread} Thread with ID=\"{Thread.CurrentThread.ManagedThreadId}\"\n" +
$"The current DISPATCHER_THREAD Thread has the ID=\"{Application.Current.Dispatcher.Thread.ManagedThreadId}\"";
this._dialogCoordinator.ShowMessageAsync(this, $"Message from VM created by {startingThread}", message).ContinueWith(t => Console.WriteLine(t.Result));
};
}
public ICommand ShowProgressDialogCommand { get; }
private async void RunProgressFromVm()
{
var controller = await this._dialogCoordinator.ShowProgressAsync(this, "Progress from VM", "Progressing all the things, wait 3 seconds");
controller.SetIndeterminate();
await Task.Delay(3000);
await controller.CloseAsync();
}
private static void PerformDialogCoordinatorAction(Action action, bool runInMainThread)
{
if (!runInMainThread)
{
Task.Factory.StartNew(action);
}
else
{
action();
}
}
public ICommand ShowCustomDialogCommand { get; }
private async void RunCustomFromVm()
{
var customDialog = new CustomDialog { Title = "Custom Dialog" };
var dataContext = new CustomDialogExampleContent(instance =>
{
this._dialogCoordinator.HideMetroDialogAsync(this, customDialog);
System.Diagnostics.Debug.WriteLine(instance.FirstName);
});
customDialog.Content = new CustomDialogExample { DataContext = dataContext };
await this._dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
}
public ObservableCollection<ThemeResource> ThemeResources { get; }
public bool AnimateOnPositionChange
{
get => this._animateOnPositionChange;
set => this.Set(ref this._animateOnPositionChange, value);
}
public void UpdateThemeResources()
{
this.ThemeResources.Clear();
if (Application.Current.MainWindow != null)
{
var theme = ThemeManager.Current.DetectTheme(Application.Current.MainWindow);
if (theme is not null)
{
var libraryTheme = theme.LibraryThemes.FirstOrDefault(x => x.Origin == "MahApps.Metro");
var resourceDictionary = libraryTheme?.Resources.MergedDictionaries.FirstOrDefault();
if (resourceDictionary != null)
{
foreach (var dictionaryEntry in resourceDictionary.OfType<DictionaryEntry>())
{
this.ThemeResources.Add(new ThemeResource(theme, libraryTheme!, resourceDictionary, dictionaryEntry));
}
}
}
}
}
public Uri[] FlipViewImages { get; set; }
public class RandomDataTemplateSelector : DataTemplateSelector
{
public DataTemplate? TemplateOne { get; set; }
public override DataTemplate? SelectTemplate(object item, DependencyObject container)
{
return this.TemplateOne;
}
}
private HotKey? _hotKey = new HotKey(Key.Home, ModifierKeys.Control | ModifierKeys.Shift);
public HotKey? HotKey
{
get => this._hotKey;
set
{
if (this.Set(ref this._hotKey, value))
{
if (value != null && value.Key != Key.None)
{
HotkeyManager.Current.AddOrReplace("demo", value.Key, value.ModifierKeys, async (sender, e) => await this.OnHotKey(sender, e));
}
else
{
HotkeyManager.Current.Remove("demo");
}
}
}
}
private async Task OnHotKey(object? sender, HotkeyEventArgs e)
{
await this._dialogCoordinator.ShowMessageAsync(this,
"Hotkey pressed",
"You pressed the hotkey '" + this.HotKey + "' registered with the name '" + e.Name + "'");
}
public ICommand ToggleIconScalingCommand { get; }
private void ToggleIconScaling(MultiFrameImageMode? multiFrameImageMode)
{
((MetroWindow)Application.Current.MainWindow).IconScalingMode = multiFrameImageMode!.Value;
this.OnPropertyChanged(nameof(this.IsScaleDownLargerFrame));
this.OnPropertyChanged(nameof(this.IsNoScaleSmallerFrame));
}
public bool IsScaleDownLargerFrame => ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.ScaleDownLargerFrame;
public bool IsNoScaleSmallerFrame => ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.NoScaleSmallerFrame;
public bool IsToggleSwitchVisible { get; set; }
public ObservableCollection<Models.Animals> Animals { get; } = new(Models.Animals.GenerateDate());
public ObservableCollection<Models.Animals> SelectedAnimals { get; } = new();
private object? myFavoriteAnimal;
[Display(Prompt = "Select your favorite animal(s)")]
public object? MyFavoriteAnimal
{
get => this.myFavoriteAnimal;
set => this.Set(ref this.myFavoriteAnimal, value);
}
public ObjectParser? MyObjectParser { get; }
}
}