/
ViewModelBase.cs
1550 lines (1314 loc) · 64 KB
/
ViewModelBase.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
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
namespace Catel.MVVM
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Auditing;
using Collections;
using Data;
using IoC;
using Logging;
using Reflection;
using Services;
/// <summary>
/// View model base for MVVM implementations. This class is based on the <see cref="ModelBase" />, and supports all
/// common interfaces used by WPF.
/// </summary>
/// <remarks>This view model base does not add any services.</remarks>
public abstract partial class ViewModelBase : ValidatableModelBase, IRelationalViewModel, IUniqueIdentifyable
{
/// <summary>
/// The log.
/// </summary>
private static readonly ILog Log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Dictionary containing the view model metadata of a view model type so it has to be calculated only once.
/// </summary>
private static readonly ConcurrentDictionary<Type, ViewModelMetadata> _metaData = new ConcurrentDictionary<Type, ViewModelMetadata>();
/// <summary>
/// The object adapter responsible for the property mappings.
/// </summary>
protected readonly IObjectAdapter _objectAdapter;
/// <summary>
/// The dispatcher service used to dispatch all calls.
/// </summary>
private readonly IDispatcherService _dispatcherService;
/// <summary>
/// Value indicating whether the multiple modules warning should be ignored.
/// </summary>
private readonly bool _ignoreMultipleModelsWarning;
/// <summary>
/// Value indicating whether the view model attributes are initialized.
/// </summary>
private bool _areViewModelAttributesIntialized;
private readonly object _modelLock = new object();
/// <summary>
/// Dictionary of available models inside the view model.
/// </summary>
private readonly Dictionary<string, object?> _modelObjects = new Dictionary<string, object?>();
/// <summary>
/// Dictionary with info about the available models inside the view model.
/// </summary>
private readonly Dictionary<string, ModelInfo> _modelObjectsInfo = new Dictionary<string, ModelInfo>();
/// <summary>
/// Dictionary with data error info about a specific model.
/// </summary>
private readonly Dictionary<string, ModelErrorInfo> _modelErrorInfo = new Dictionary<string, ModelErrorInfo>();
/// <summary>
/// List of child view models which can be registed by the <c>RegisterChildViewModel</c> method.
/// </summary>
internal readonly List<IViewModel> ChildViewModels = new List<IViewModel>();
/// <summary>
/// Value to determine whether child view models have errors or not.
/// </summary>
private bool _childViewModelsHaveErrors;
/// <summary>
/// Gets the view model manager.
/// </summary>
/// <value>The view model manager.</value>
protected static readonly IViewModelManager ViewModelManager;
/// <summary>
/// Mappings from view model properties to models and their properties.
/// </summary>
private readonly Dictionary<string, ViewModelToModelMapping> _viewModelToModelMap = new Dictionary<string, ViewModelToModelMapping>();
/// <summary>
/// The backing field for the title property.
/// </summary>
private string _title;
private readonly IObjectIdGenerator<int> _objectIdGenerator;
/// <summary>
/// Initializes static members of the <see cref="ViewModelBase" /> class.
/// </summary>
static ViewModelBase()
{
var serviceLocator = IoC.ServiceLocator.Default;
serviceLocator.RegisterTypeIfNotYetRegistered<IViewModelManager, ViewModelManager>();
ViewModelManager = serviceLocator.ResolveRequiredType<IViewModelManager>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelBase"/> class.
/// </summary>
/// <exception cref="ModelNotRegisteredException">A mapped model is not registered.</exception>
/// <exception cref="PropertyNotFoundInModelException">A mapped model property is not found.</exception>
protected ViewModelBase()
: this(true, false, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelBase"/> class.
/// </summary>
/// <param name="supportIEditableObject">if set to <c>true</c>, the view model will natively support models that
/// implement the <see cref="IEditableObject"/> interface.</param>
/// <param name="ignoreMultipleModelsWarning">if set to <c>true</c>, the warning when using multiple models is ignored.</param>
/// <param name="skipViewModelAttributesInitialization">
/// if set to <c>true</c>, the initialization will be skipped and must be done manually via <see cref="InitializeViewModelAttributes"/>.
/// </param>
/// <exception cref="ModelNotRegisteredException">A mapped model is not registered.</exception>
/// <exception cref="PropertyNotFoundInModelException">A mapped model property is not found.</exception>
protected ViewModelBase(bool supportIEditableObject, bool ignoreMultipleModelsWarning = false, bool skipViewModelAttributesInitialization = false)
: this(null, supportIEditableObject, ignoreMultipleModelsWarning, skipViewModelAttributesInitialization)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelBase"/> class.
/// <para/>
/// This constructor allows the injection of a custom <see cref="IServiceLocator"/>.
/// </summary>
/// <param name="serviceLocator">The service locator to inject. If <c>null</c>, the <see cref="Catel.IoC.ServiceLocator.Default"/> will be used.</param>
/// <param name="supportIEditableObject">if set to <c>true</c>, the view model will natively support models that
/// implement the <see cref="IEditableObject"/> interface.</param>
/// <param name="ignoreMultipleModelsWarning">if set to <c>true</c>, the warning when using multiple models is ignored.</param>
/// <param name="skipViewModelAttributesInitialization">if set to <c>true</c>, the initialization will be skipped and must be done manually via <see cref="InitializeViewModelAttributes"/>.</param>
/// <exception cref="ModelNotRegisteredException">A mapped model is not registered.</exception>
/// <exception cref="PropertyNotFoundInModelException">A mapped model property is not found.</exception>
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
protected ViewModelBase(IServiceLocator? serviceLocator, bool supportIEditableObject = true, bool ignoreMultipleModelsWarning = false, bool skipViewModelAttributesInitialization = false)
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
{
ViewModelConstructionTime = FastDateTime.Now;
if (CatelEnvironment.IsInDesignMode)
{
return;
}
_ignoreMultipleModelsWarning = ignoreMultipleModelsWarning;
if (serviceLocator is null)
{
serviceLocator = ServiceLocator.Default;
}
DependencyResolver = serviceLocator.ResolveRequiredType<IDependencyResolver>();
_objectAdapter = DependencyResolver.ResolveRequired<IObjectAdapter>();
_dispatcherService = DependencyResolver.ResolveRequired<IDispatcherService>();
var type = GetType();
// Note: we get the type *every time*, but it should be cheaper than checking the existance of the type in the
// service locator. Note that we should *not* use a callback since that will create a memory leak because the
// service locator will hold a reference to the first vm *per type*
var objectGeneratorType = GetObjectIdGeneratorType();
serviceLocator.RegisterType(typeof(IObjectIdGenerator<int>), objectGeneratorType, tag: type, registerIfAlreadyRegistered: false);
_objectIdGenerator = DependencyResolver.ResolveRequired<IObjectIdGenerator<int>>(type);
UniqueIdentifier = GetObjectId(_objectIdGenerator);
Log.Debug("Creating view model of type '{0}' with unique identifier {1}", type.Name, BoxingCache.GetBoxedValue(UniqueIdentifier));
ValidateModelsOnInitialization = true;
ViewModelCommandManager = MVVM.ViewModelCommandManager.Create(this);
ViewModelCommandManager.AddHandler(async (viewModel, propertyName, command, commandParameter) =>
{
var eventArgs = new CommandExecutedEventArgs((ICatelCommand)command, commandParameter, propertyName);
await CommandExecutedAsync.SafeInvokeAsync(this, eventArgs);
});
DeferValidationUntilFirstSaveCall = true;
InvalidateCommandsOnPropertyChanged = true;
SupportIEditableObject = supportIEditableObject;
// Temporarily suspend validation
using (SuspendValidations(false))
{
if (!skipViewModelAttributesInitialization)
{
InitializeViewModelAttributes();
}
ViewModelManager.RegisterViewModelInstance(this);
InitializeThrottling();
}
// As a last step, enable the auditors (we don't need change notifications of previous properties, etc)
AuditingHelper.RegisterViewModel(this);
}
/// <summary>
/// Occurs when the view model has been initialized.
/// </summary>
public event AsyncEventHandler<EventArgs>? InitializedAsync;
/// <summary>
/// Occurs when a command on the view model has been executed.
/// </summary>
public event AsyncEventHandler<CommandExecutedEventArgs>? CommandExecutedAsync;
/// <summary>
/// Occurs when the view model is about to be saved.
/// </summary>
public event AsyncEventHandler<SavingEventArgs>? SavingAsync;
/// <summary>
/// Occurs when the view model is saved successfully.
/// </summary>
public event AsyncEventHandler<EventArgs>? SavedAsync;
/// <summary>
/// Occurs when the view model is about to be canceled.
/// </summary>
public event AsyncEventHandler<CancelingEventArgs>? CancelingAsync;
/// <summary>
/// Occurrs when the view model is canceled.
/// </summary>
public event AsyncEventHandler<EventArgs>? CanceledAsync;
/// <summary>
/// Occurs when the view model is being closed.
/// </summary>
public event AsyncEventHandler<EventArgs>? ClosingAsync;
/// <summary>
/// Occurs when the view model has just been closed.
/// </summary>
public event AsyncEventHandler<ViewModelClosedEventArgs>? ClosedAsync;
/// <summary>
/// Gets the unique identifier of the view model.
/// </summary>
/// <value>The unique identifier.</value>
[ExcludeFromValidation]
public int UniqueIdentifier { get; private set; }
/// <summary>
/// Gets the view model construction time, which is used to get unique instances of view models.
/// </summary>
/// <value>The view model construction time.</value>
[ExcludeFromValidation]
public DateTime ViewModelConstructionTime { get; private set; }
/// <summary>
/// Gets the parent view model.
/// </summary>
/// <value>The parent view model.</value>
[ExcludeFromValidation]
public IViewModel? ParentViewModel { get; private set; }
/// <summary>
/// Gets the <see cref="ViewModelCommandManager"/> of this view model.
/// </summary>
/// <value>The <see cref="ViewModelCommandManager"/>.</value>
[ExcludeFromValidation]
protected internal IViewModelCommandManager ViewModelCommandManager { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether the commands should automatically be invalidated on a property change.
/// <para />
/// If this property is <c>false</c>, properties should either be invalidated by the .NET Framework or by a manual
/// call to the <see cref="IViewModelCommandManager.InvalidateCommands(bool)"/> method.
/// </summary>
/// <value>
/// <c>true</c> if the commands should automatically be invalidated on a property change; otherwise, <c>false</c>.
/// </value>
[ExcludeFromValidation]
protected bool InvalidateCommandsOnPropertyChanged { get; set; }
/// <summary>
/// Gets or sets a value indicating whether models that implement <see cref="IEditableObject"/> are supported correctly.
/// </summary>
/// <value>
/// <c>true</c> if models that implement <see cref="IEditableObject"/> are supported correctly; otherwise, <c>false</c>.
/// </value>
[ExcludeFromValidation]
private bool SupportIEditableObject { get; set; }
/// <summary>
/// Defines the maximum allowed time used by the save, cancel and close actions of the view model.
/// <para/>
/// The default value is <see cref="IViewModelExtensions.ViewModelActionAwaitTimeoutInMilliseconds"/>
/// </summary>
[ExcludeFromValidation]
protected internal int ViewModelActionAwaitTimeoutInMilliseconds { get; set; } = IViewModelExtensions.ViewModelActionAwaitTimeoutInMilliseconds;
/// <summary>
/// Gets a value indicating whether this object is currently initializing.
/// </summary>
/// <value>
/// <c>true</c> if this object is currently initializing; otherwise, <c>false</c>.
/// </value>
[ExcludeFromValidation]
protected internal bool IsInitializing { get; private set; }
/// <summary>
/// Gets a value indicating whether this object is initialized.
/// </summary>
/// <value>
/// <c>true</c> if this object is initialized; otherwise, <c>false</c>.
/// </value>
[ExcludeFromValidation]
protected internal bool IsInitialized { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is currently canceling.
/// </summary>
[ExcludeFromValidation]
protected internal bool IsCanceling { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is currently saving.
/// </summary>
[ExcludeFromValidation]
protected internal bool IsSaving { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is closing.
/// </summary>
/// <value><c>true</c> if this instance is closing; otherwise, <c>false</c>.</value>
protected internal bool IsClosing { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is closed. If a view model is closed, calling
/// <see cref="CancelViewModelAsync"/>, <see cref="SaveViewModelAsync"/> or <see cref="CloseViewModelAsync"/>
/// will have no effect.
/// </summary>
/// <value><c>true</c> if the view model is closed; otherwise, <c>false</c>.</value>
[ExcludeFromValidation]
public bool IsClosed { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is saved at least once.
/// </summary>
/// <value><c>true</c> if this instance is saved at least once; otherwise, <c>false</c>.</value>
[ExcludeFromValidation]
public bool IsSaved { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is canceled at least once.
/// </summary>
/// <value><c>true</c> if this instance is canceled at least once; otherwise, <c>false</c>.</value>
[ExcludeFromValidation]
public bool IsCanceled { get; private set; }
/// <summary>
/// Gets the title of the view model.
/// </summary>
/// <value>The title.</value>
[ExcludeFromValidation]
public virtual string Title
{
get { return _title; }
protected set
{
_title = value;
RaisePropertyChanged(nameof(Title));
}
}
/// <summary>
/// Gets a value indicating whether this object contains any field or business errors.
/// </summary>
/// <value>
/// <c>true</c> if this instance has errors; otherwise, <c>false</c>.
/// </value>
[ExcludeFromValidation]
public override bool HasErrors
{
get
{
if (base.HasErrors)
{
return true;
}
if (_childViewModelsHaveErrors)
{
return true;
}
return false;
}
}
/// <summary>
/// Gets the dependency resolver.
/// </summary>
/// <value>The dependency resolver.</value>
[ExcludeFromValidation]
protected IDependencyResolver DependencyResolver { get; private set; }
partial void InitializeThrottling();
partial void UninitializeThrottling();
/// <summary>
/// Converts the object to a string.
/// </summary>
/// <returns>System.String.</returns>
public override string ToString()
{
return $"{GetType().FullName} (ID = {UniqueIdentifier})";
}
/// <summary>
/// Initializes the properties with attributes.
/// </summary>
private void InitializePropertiesWithAttributes()
{
var viewModelType = GetType();
var metaData = GetViewModelMetaData(viewModelType);
lock (_modelLock)
{
_modelObjectsInfo.AddRange(metaData.Models);
}
_viewModelToModelMap.AddRange(metaData.Mappings);
}
/// <summary>
/// Initializes the view model meta data.
/// <para />
/// This method only initializes the meta data once per view model type. If a type is already initialized,
/// this method will immediately return.
/// </summary>
/// <param name="viewModelType">Type of the view model.</param>
/// <returns>ViewModelMetadata.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="viewModelType" /> is <c>null</c>.</exception>
private static ViewModelMetadata GetViewModelMetaData(Type viewModelType)
{
return _metaData.GetOrAdd(viewModelType, CreateViewModelMetaData);
}
private static ViewModelMetadata CreateViewModelMetaData(Type viewModelType)
{
var properties = new List<PropertyInfo>();
var bindingFlags = BindingFlagsHelper.GetFinalBindingFlags(true, false, true);
properties.AddRange(viewModelType.GetPropertiesEx(bindingFlags));
var modelObjectsInfo = new Dictionary<string, ModelInfo>();
var viewModelToModelMap = new Dictionary<string, ViewModelToModelMapping>();
var modelNames = (from propertyInfo in properties
where propertyInfo.IsDecoratedWithAttribute<ModelAttribute>()
select propertyInfo.Name).ToList();
// Important: iterate twice, models first, they are needed to get the model type
foreach (var propertyInfo in properties)
{
var modelAttribute = propertyInfo.GetCustomAttributeEx<ModelAttribute>(true);
if (modelAttribute is not null)
{
modelObjectsInfo.Add(propertyInfo.Name, new ModelInfo(propertyInfo, modelAttribute));
}
}
// View model to model mappings
foreach (var propertyInfo in properties)
{
var viewModelToModelAttribute = propertyInfo.GetCustomAttributeEx<ViewModelToModelAttribute>(true);
if (viewModelToModelAttribute is not null)
{
if (string.IsNullOrEmpty(viewModelToModelAttribute.Property))
{
// Assume the property name in the model is the same as in the view model
viewModelToModelAttribute.Property = propertyInfo.Name;
}
if (string.IsNullOrWhiteSpace(viewModelToModelAttribute.Model))
{
Log.Debug("ViewToViewModel is missing the Model name, searching for the right model automatically");
if (modelNames.Count != 1)
{
throw Log.ErrorAndCreateException<InvalidOperationException>($"It is only possible to automatically select the right model if there is 1 model. There are '{modelNames.Count.ToString()}' models, so please specify the model name explicitly.");
}
viewModelToModelAttribute.Model = modelNames[0];
}
if (!viewModelToModelMap.ContainsKey(propertyInfo.Name))
{
var modelProperty = modelObjectsInfo[viewModelToModelAttribute.Model];
viewModelToModelMap.Add(propertyInfo.Name, new ViewModelToModelMapping(propertyInfo, modelProperty.PropertyType, viewModelToModelAttribute));
}
}
}
// Validation (1 time for all view models of the same type)
foreach (var viewModelToModelMapping in viewModelToModelMap)
{
var mapping = viewModelToModelMapping.Value;
if (!modelObjectsInfo.ContainsKey(mapping.ModelProperty))
{
throw Log.ErrorAndCreateException(msg => new ModelNotRegisteredException(mapping.ModelProperty, mapping.ViewModelProperty),
"There is no model '{0}' registered with the model attribute, so the ViewModelToModel attribute on property '{1}' is invalid",
mapping.ModelProperty, mapping.ViewModelProperty);
}
var viewModelPropertyType = viewModelToModelMapping.Value.ViewModelPropertyType;
var modelPropertyType = viewModelToModelMapping.Value.ModelPropertyType;
var modelPropertyPropertyTypes = new Type[mapping.ValueProperties.Length];
for (var i = 0; i < mapping.ValueProperties.Length; i++)
{
var valueProperty = mapping.ValueProperties[i];
var modelPropertyPropertyInfo = modelPropertyType.GetPropertyEx(valueProperty);
if (modelPropertyPropertyInfo is null)
{
Log.Warning("Mapped viewmodel property '{0}' to model property '{1}' is invalid because property '{1}' is not found on the model '{2}'.\n\n" +
"If the property is defined in a sub-interface, reflection does not return it as a valid property. If this is the case, you can safely ignore this warning",
mapping.ViewModelProperty, valueProperty, mapping.ModelProperty);
modelPropertyPropertyTypes[i] = typeof(object);
}
else
{
modelPropertyPropertyTypes[i] = modelPropertyPropertyInfo.PropertyType;
}
}
if (!mapping.Converter.CanConvert(modelPropertyPropertyTypes, viewModelPropertyType, viewModelType))
{
Log.Warning("Property '{0}' mapped on model properties '{1}' cannot be converted via given converter '{2}'",
mapping.ViewModelProperty, string.Join(", ", mapping.ValueProperties), mapping.ConverterType);
}
}
return new ViewModelMetadata(viewModelType, modelObjectsInfo, viewModelToModelMap);
}
/// <summary>
/// Initializes the view model attributes, such as the <see cref="ModelAttribute"/> and
/// <see cref="ViewModelToModelAttribute"/>.
/// <para />
/// This method is automatically invoked by the constructor. Sometimes, dynamic properties
/// are registered after the constructor. Therefore, it is possible to skip the initialization
/// of the attributes and handle this manually.
/// </summary>
/// <exception cref="ModelNotRegisteredException">A mapped model is not registered.</exception>
/// <exception cref="PropertyNotFoundInModelException">A mapped model property is not found.</exception>
protected void InitializeViewModelAttributes()
{
if (_areViewModelAttributesIntialized)
{
return;
}
_areViewModelAttributesIntialized = true;
using (SuspendValidations(false))
{
InitializePropertiesWithAttributes();
lock (_modelLock)
{
foreach (var modelInfo in _modelObjectsInfo)
{
_modelObjects.Add(modelInfo.Key, null);
}
}
if (SupportIEditableObject)
{
lock (_modelLock)
{
foreach (var modelKeyValuePair in _modelObjects)
{
if (_modelObjectsInfo[modelKeyValuePair.Key].SupportIEditableObject)
{
if (modelKeyValuePair.Value is not null)
{
var modelKeyValuePairValueAsModelBaseBase = modelKeyValuePair.Value as IModel;
if ((modelKeyValuePairValueAsModelBaseBase is null) || !modelKeyValuePairValueAsModelBaseBase.IsInEditSession)
{
EditableObjectHelper.BeginEditObject(modelKeyValuePair.Value);
}
}
}
}
}
}
if (!_ignoreMultipleModelsWarning)
{
lock (_modelLock)
{
if (_modelObjects.Count > 1)
{
Log.Warning("The view model {0} implements {1} models.\n\n" +
"Normally, a view model only implements 1 model so make sure you are using the Model attribute correctly. If the Model attribute is used correctly (on models only), this warning can be ignored by using a constructor overload.",
GetType().Name, BoxingCache.GetBoxedValue(_modelObjects.Count));
}
}
}
}
}
/// <summary>
/// Sets the new parent view model of this view model.
/// </summary>
/// <param name="parentViewModel">The parent view model.</param>
void IRelationalViewModel.SetParentViewModel(IViewModel? parentViewModel)
{
if (!ObjectHelper.AreEqualReferences(ParentViewModel, parentViewModel))
{
ParentViewModel = parentViewModel;
var parentVm = parentViewModel as ViewModelBase;
if (parentVm is not null)
{
var value = DeferValidationUntilFirstSaveCall;
var parentVmValue = parentVm.DeferValidationUntilFirstSaveCall;
if (value != parentVmValue)
{
Log.Debug($"DeferValidationUntilFirstCall is '{BoxingCache.GetBoxedValue(value)}', but overriding value using parent view model value '{BoxingCache.GetBoxedValue(parentVmValue)}'");
DeferValidationUntilFirstSaveCall = parentVmValue;
}
}
RaisePropertyChanged(nameof(ParentViewModel));
}
}
/// <summary>
/// Registers a child view model to this view model. When a view model is registered as a child view model, it will
/// receive all notifications from this view model and be notified of any validation changes.
/// </summary>
/// <param name="childViewModel">The child view model.</param>
/// <exception cref="ArgumentNullException">The <paramref name="childViewModel"/> is <c>null</c>.</exception>
void IRelationalViewModel.RegisterChildViewModel(IViewModel childViewModel)
{
ArgumentNullException.ThrowIfNull(childViewModel);
lock (ChildViewModels)
{
if (ObjectHelper.AreEqualReferences(this, childViewModel))
{
return;
}
var childViewModels = ChildViewModels;
if (!childViewModels.Contains(childViewModel))
{
childViewModels.Add(childViewModel);
childViewModel.PropertyChanged += OnChildViewModelPropertyChanged;
childViewModel.ClosedAsync += OnChildViewModelClosedAsync;
}
var validate = false;
// The ViewModelBase.HasErrors has a diff implementation than IModelValidation, this might (or should) be changed
// but this is the easiest and most reliable way to make it work now
var viewModelBase = childViewModel as ViewModelBase;
if (viewModelBase is not null && viewModelBase.HasErrors)
{
validate = true;
}
else
{
var validationContext = ((IValidatableModel)childViewModel).ValidationContext;
if (validationContext is not null)
{
if (validationContext.HasErrors || validationContext.HasWarnings)
{
validate = true;
}
}
}
if (validate)
{
Validate();
}
}
}
/// <summary>
/// Called when a property has changed on the child view model.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
private void OnChildViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(HasErrors) || e.PropertyName == nameof(HasWarnings))
{
Validate();
}
if (InvalidateCommandsOnPropertyChanged)
{
ViewModelCommandManager.InvalidateCommands();
}
}
/// <summary>
/// Called when the child view model is closed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private Task OnChildViewModelClosedAsync(object? sender, EventArgs e)
{
var viewModel = sender as IViewModel;
if (viewModel is not null)
{
((IRelationalViewModel)this).UnregisterChildViewModel(viewModel);
}
return Task.CompletedTask;
}
/// <summary>
/// Unregisters the child view model. This means that the child view model will no longer receive any notifications
/// from this view model as parent view model, nor will it be included in any validation calls in this view model.
/// </summary>
/// <param name="childViewModel">The child.</param>
/// <exception cref="ArgumentNullException">The <paramref name="childViewModel"/> is <c>null</c>.</exception>
void IRelationalViewModel.UnregisterChildViewModel(IViewModel childViewModel)
{
ArgumentNullException.ThrowIfNull(childViewModel);
lock (ChildViewModels)
{
var index = ChildViewModels.IndexOf(childViewModel);
if (index == -1)
{
return;
}
childViewModel.PropertyChanged -= OnChildViewModelPropertyChanged;
childViewModel.ClosedAsync -= OnChildViewModelClosedAsync;
ChildViewModels.RemoveAt(index);
}
}
/// <summary>
/// Gets the child view models of this view model.
/// </summary>
/// <returns>An enumerable of current child view models.</returns>
protected IEnumerable<IViewModel> GetChildViewModels()
{
lock (ChildViewModels)
{
return ChildViewModels.ToArray();
}
}
/// <summary>
/// Gets all models that are decorated with the <see cref="ModelAttribute"/>.
/// </summary>
/// <returns>Array of models.</returns>
protected object[] GetAllModels()
{
lock (_modelLock)
{
return _modelObjects.Values.Where(x => x is not null).Cast<object>().ToArray();
}
}
/// <summary>
/// Updates the view model to model mappings that are defined as <see cref="ViewModelToModelMode.Explicit"/>.
/// </summary>
protected void UpdateExplicitViewModelToModelMappings()
{
Log.Debug("Updating all explicit view model to model mappings");
var explicitMappings = (from mapping in _viewModelToModelMap
where mapping.Value.Mode == ViewModelToModelMode.Explicit
select mapping.Value);
foreach (var mapping in explicitMappings)
{
var model = _modelObjects[mapping.ModelProperty];
if (model is not null)
{
var value = GetValue<object>(mapping.ViewModelProperty);
var modelValues = mapping.Converter.ConvertBack(value, this);
for (var i = 0; i < mapping.ValueProperties.Length; i++)
{
if (_objectAdapter.TrySetMemberValue(model, mapping.ValueProperties[i], modelValues[i]))
{
Log.Debug("Updated property '{0}' on model type '{1}' to '{2}'", mapping.ValueProperties, model.GetType().Name, ObjectToStringHelper.ToString(value));
}
else
{
Log.Warning("Failed to set property '{0}' on model type '{1}'", mapping.ValueProperties, model.GetType().Name);
}
}
}
}
Log.Debug("Updated all explicit view model to model mappings");
}
/// <summary>
/// Called when a property value has changed.
/// </summary>
/// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (IsSaving || IsCanceling || IsClosing || IsClosed)
{
return;
}
if (string.IsNullOrEmpty(e.PropertyName))
{
return;
}
base.OnPropertyChanged(e);
lock (_modelLock)
{
if (_modelObjects.ContainsKey(e.PropertyName))
{
// Clean up old model
var oldModelValue = _modelObjects[e.PropertyName];
if (oldModelValue is not null)
{
UninitializeModelInternal(e.PropertyName, oldModelValue, ModelCleanUpMode.CancelEdit);
}
var newModelValue = GetValue<object?>(e.PropertyName);
_modelObjects[e.PropertyName] = newModelValue;
if (newModelValue is not null)
{
InitializeModelInternal(e.PropertyName, newModelValue);
}
// Since the model has been changed, copy all values from the model to the view model
foreach (var viewModelToModelMap in _viewModelToModelMap)
{
var mapping = viewModelToModelMap.Value;
var converter = mapping.Converter;
if (string.CompareOrdinal(mapping.ModelProperty, e.PropertyName) == 0)
{
var values = new object?[mapping.ValueProperties.Length];
if (newModelValue is not null)
{
// We have a new model, ignore OneWayToSource
if (mapping.Mode == ViewModelToModelMode.OneWayToSource)
{
continue;
}
for (var index = 0; index < mapping.ValueProperties.Length; index++)
{
var property = mapping.ValueProperties[index];
if (_objectAdapter.TryGetMemberValue(newModelValue, property, out object? memberValue))
{
values[index] = memberValue;
}
}
}
else
{
var property = mapping.ViewModelProperty;
var propertyData = GetPropertyData(property);
values[0] = propertyData.GetDefaultValue();
}
values[0] = converter.Convert(values, this);
SetValue(mapping.ViewModelProperty, values[0], true);
}
}
}
}
// If we are validating, don't map view model values back to the model
if (!IsValidating)
{
var validate = false;
if (_viewModelToModelMap.TryGetValue(e.PropertyName, out var mapping))
{
lock (_modelLock)
{
var model = _modelObjects[mapping.ModelProperty];
if (model is not null)
{
var modelInfo = _modelObjectsInfo[mapping.ModelProperty];
if (!modelInfo.IsCanceling)
{
var viewModelValue = GetValue<object>(e.PropertyName);
var propertiesToSet = mapping.ValueProperties;
if (_modelErrorInfo.TryGetValue(mapping.ModelProperty, out var modelErrorInfo))
{
mapping.ValueProperties.ForEach(modelErrorInfo.ClearDefaultErrors);
}
// Only TwoWay, OneWayToSource mappings should be mapped
if ((mapping.Mode == ViewModelToModelMode.TwoWay) || (mapping.Mode == ViewModelToModelMode.OneWayToSource))
{
var valuesToSet = mapping.Converter.ConvertBack(viewModelValue, this);
if (propertiesToSet.Length != valuesToSet.Length)
{
Log.Error("Properties - values count mismatch, properties '{0}', values '{1}'",
string.Join(", ", propertiesToSet), string.Join(", ", valuesToSet));
}
for (var index = 0; index < propertiesToSet.Length && index < valuesToSet.Length; index++)
{
try
{
mapping.IgnoredProperties.AddRange(propertiesToSet);
var propertyToUpdate = propertiesToSet[index];
var valueToSet = valuesToSet[index];
// Check equality first, see https://github.com/Catel/Catel/issues/2164
// If we fail, just set it anyways (keep old behavior)
if (_objectAdapter.TryGetMemberValue<object?>(model, propertyToUpdate, out var currentValue))
{
if (ObjectHelper.AreEqual(currentValue, valueToSet))
{
continue;
}
}
if (_objectAdapter.TrySetMemberValue(model, propertyToUpdate, valueToSet))
{
Log.Debug("Updated property '{0}' on model type '{1}' to '{2}'", propertiesToSet[index], model.GetType().Name, ObjectToStringHelper.ToString(valueToSet));
// Force validation, see https://github.com/Catel/Catel/issues/1108
validate = true;
}
else
{
Log.Warning("Failed to set property '{0}' on model type '{1}'", propertiesToSet[index], model.GetType().Name);
}
}
finally
{
foreach (var propertyToSet in propertiesToSet)
{
mapping.IgnoredProperties.Remove(propertyToSet);
}
}
}
}
}
}
else
{
Log.Warning("Value for model property '{0}' is null, cannot map properties from view model to model", mapping.ModelProperty);
}
}
}
if (validate)
{
// Model was updated successfully, make sure to revalidate, fixes https://github.com/Catel/Catel/issues/1108
Validate(true);
}
}
if (InvalidateCommandsOnPropertyChanged)
{
ViewModelCommandManager.InvalidateCommands();