-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
DependencyObject.cs
3571 lines (3130 loc) · 150 KB
/
DependencyObject.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
// 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.
// #define NESTED_OPERATIONS_CHECK
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization; // For CultureInfo.InvariantCulture
using System.Reflection;
using System.Windows.Threading;
using MS.Utility;
using MS.Internal;
using MS.Internal.WindowsBase;
using System.Windows.Markup;
namespace System.Windows
{
/// <summary>
/// DependencyObject is an object that participates in the property dependency system
/// </summary>
/// <remarks>
/// DependencyObject encompasses all property engine services. It's primary function
/// is providing facilities to compute a property's value based on other properties.<para/>
///
/// The Property Engine introduces a new type of property: attached properties. Attached
/// properties are identified via <see cref="DependencyProperty"/> and are read and
/// written using GetValue and SetValue.<para/>
///
/// Attached properties may be set and queried on any DependencyObject-derived type.<para/>
///
/// <see cref="Expression"/> is used to define relationships between properties. SetValue
/// is used to apply the Expression to the property on the instance.
///
/// DependencyObject services include the following:
/// <para/>
/// <list type="bullet">
/// <item>Dependency-based property value evaluation through Expressions</item>
/// <item>Property invalidation dependent traversal through Expressions</item>
/// <item>Attached property support</item>
/// <item>Invalidation notification services</item>
/// </list>
/// </remarks>
/// This attribute allows designers looking at metadata through TypeDescriptor to see dependency properties
/// and attached properties.
[System.ComponentModel.TypeDescriptionProvider(typeof(MS.Internal.ComponentModel.DependencyObjectProvider))]
[System.Windows.Markup.NameScopeProperty("NameScope", typeof(System.Windows.NameScope))]
public class DependencyObject : DispatcherObject
{
/// <summary>
/// Default DependencyObject constructor
/// </summary>
/// <remarks>
/// Automatic determination of current Dispatcher. Use alternative constructor
/// that accepts a Dispatcher for best performance.
/// </remarks>
public DependencyObject()
{
Initialize();
}
/// <summary>Returns the DType that represents the CLR type of this instance</summary>
public DependencyObjectType DependencyObjectType
{
get
{
if (_dType == null)
{
// Specialized type identification
_dType = DependencyObjectType.FromSystemTypeInternal(GetType());
}
// Do not call VerifyAccess because this method is trivial.
return _dType;
}
}
private void Initialize()
{
CanBeInheritanceContext = true;
CanModifyEffectiveValues = true;
}
/// <summary>
/// Makes this object Read-Only state of this object; when in a Read-Only state, SetValue is not permitted,
/// though the effective value for a property may change.
/// </summary>
[FriendAccessAllowed] // Built into Base, also used by Framework.
internal virtual void Seal()
{
Debug.Assert(!(this is Freezable), "A Freezable should not call DO's implementation of Seal()");
// Currently DependencyObject.Seal() is semantically different than Freezable.Freeze().
// Though freezing implies sealing the reverse isn't true. The salient difference
// here is that sealing a DependencyObject does not force all DPs on that object to
// also be sealed. Thus, when we Seal(), we promote all cached values to locally set
// so that the user can continue to modify them. Freezable types instead strip off
// the promotion handler and freeze the cached default. Note that when / if we make
// Seal() == Freeze this code should go away in favor of the behavior used for Freezables.
PropertyMetadata.PromoteAllCachedDefaultValues(this);
// Since Freeze doesn't call Seal the code below will also be duplicated in Freeze().
// Since this object no longer changes it won't be able to notify dependents
DependentListMapField.ClearValue(this);
DO_Sealed = true;
}
/// <summary>
/// Indicates whether or not this object is in a Read-Only state; when in a Read-Only state, SetValue is not permitted,
/// though the effective value for a property may change.
/// </summary>
public bool IsSealed
{
get
{
return DO_Sealed;
}
}
/// <summary>
/// We override Equals() to seal it to prevent custom Equals()
/// implementations.
///
/// There are only two scenarios where overriding Equals makes
/// sense:
///
/// 1. You are a value type (passed by copy).
/// 2. You are an immutable reference type (e.g., System.String).
///
/// Otherwise you are going to cause problems with keyed and
/// some types of sorted datastructures because your values
/// can mutate to be equals or not equals while they reside in
/// the store (bad news for System.Collections(.Generic)).
///
/// Furthermore, defining equality for two DOs is a very slippery
/// slope. Are two brushes "equal" if they both paint red? What
/// if one is only red this frame because it is animated? What if
/// one is databound? What if one is frozen? ...and so on.
///
/// Since a DO can never be immutable (attached properties, etc.)
/// it makes sense to disallow overriding of Equals.
/// </summary>
public override sealed bool Equals(Object obj)
{
return base.Equals(obj);
}
/// <summary>
/// CS0659: Required when overriding Equals(). Overriding
/// GetHashCode() is a bad idea for similar reasons.
/// </summary>
public override sealed int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Retrieve the value of a property
/// </summary>
/// <param name="dp">Dependency property</param>
/// <returns>The computed value</returns>
public object GetValue(DependencyProperty dp)
{
// Do not allow foreign threads access.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
this.VerifyAccess();
if (dp == null)
{
throw new ArgumentNullException("dp");
}
// Call Forwarded
return GetValueEntry(
LookupEntry(dp.GlobalIndex),
dp,
null,
RequestFlags.FullyResolved).Value;
}
/// <summary>
/// This overload of GetValue returns UnsetValue if the property doesn't
/// have an entry in the _effectiveValues. This way we will avoid inheriting
/// the default value from the parent.
/// </summary>
[FriendAccessAllowed] // Built into Base, also used by Core.
internal EffectiveValueEntry GetValueEntry(
EntryIndex entryIndex,
DependencyProperty dp,
PropertyMetadata metadata,
RequestFlags requests)
{
EffectiveValueEntry entry;
if (dp.ReadOnly)
{
if (metadata == null)
{
metadata = dp.GetMetadata(DependencyObjectType);
}
GetReadOnlyValueCallback getValueCallback = metadata.GetReadOnlyValueCallback;
if (getValueCallback != null)
{
BaseValueSourceInternal valueSource;
entry = new EffectiveValueEntry(dp);
entry.Value = getValueCallback(this, out valueSource);
entry.BaseValueSourceInternal = valueSource;
return entry;
}
}
if (entryIndex.Found)
{
if ((requests & RequestFlags.RawEntry) != 0)
{
entry = _effectiveValues[entryIndex.Index];
}
else
{
entry = GetEffectiveValue(
entryIndex,
dp,
requests);
}
}
else
{
entry = new EffectiveValueEntry(dp, BaseValueSourceInternal.Unknown);
}
if (entry.Value == DependencyProperty.UnsetValue)
{
if (dp.IsPotentiallyInherited)
{
if (metadata == null)
{
metadata = dp.GetMetadata(DependencyObjectType);
}
if (metadata.IsInherited)
{
DependencyObject inheritanceParent = InheritanceParent;
if (inheritanceParent != null)
{
entryIndex = inheritanceParent.LookupEntry(dp.GlobalIndex);
if (entryIndex.Found)
{
entry = inheritanceParent.GetEffectiveValue(
entryIndex,
dp,
requests & RequestFlags.DeferredReferences);
entry.BaseValueSourceInternal = BaseValueSourceInternal.Inherited;
}
}
}
if (entry.Value != DependencyProperty.UnsetValue)
{
return entry;
}
}
if ((requests & RequestFlags.SkipDefault) == 0)
{
if (dp.IsPotentiallyUsingDefaultValueFactory)
{
if (metadata == null)
{
metadata = dp.GetMetadata(DependencyObjectType);
}
if (((requests & (RequestFlags.DeferredReferences | RequestFlags.RawEntry)) != 0) && metadata.UsingDefaultValueFactory)
{
entry.BaseValueSourceInternal = BaseValueSourceInternal.Default;
entry.Value = new DeferredMutableDefaultReference(metadata, this, dp);
return entry;
}
}
else if (!dp.IsDefaultValueChanged)
{
return EffectiveValueEntry.CreateDefaultValueEntry(dp, dp.DefaultMetadata.DefaultValue);
}
if (metadata == null)
{
metadata = dp.GetMetadata(DependencyObjectType);
}
return EffectiveValueEntry.CreateDefaultValueEntry(dp, metadata.GetDefaultValue(this, dp));
}
}
return entry;
}
/// <summary>
/// This overload of GetValue assumes that entryIndex is valid.
/// It also does not do the check storage on the InheritanceParent.
/// </summary>
private EffectiveValueEntry GetEffectiveValue(
EntryIndex entryIndex,
DependencyProperty dp,
RequestFlags requests)
{
EffectiveValueEntry entry = _effectiveValues[entryIndex.Index];
EffectiveValueEntry effectiveEntry = entry.GetFlattenedEntry(requests);
if (((requests & (RequestFlags.DeferredReferences | RequestFlags.RawEntry)) != 0) || !effectiveEntry.IsDeferredReference)
{
return effectiveEntry;
}
if (!entry.HasModifiers)
{
// For thread-safety, sealed DOs can't modify _effectiveValues.
Debug.Assert(!DO_Sealed, "A Sealed DO cannot be modified");
if (!entry.HasExpressionMarker)
{
// The value for this property was meant to come from a dictionary
// and the creation of that value had been deferred until this
// time for better performance. Now is the time to actually instantiate
// this value by querying it from the dictionary. Once we have the
// value we can actually replace the deferred reference marker
// with the actual value.
DeferredReference reference = (DeferredReference)entry.Value;
object value = reference.GetValue(entry.BaseValueSourceInternal);
if (!dp.IsValidValue(value))
{
throw new InvalidOperationException(SR.Format(SR.InvalidPropertyValue, value, dp.Name));
}
// Make sure the entryIndex is in sync after
// the inflation of the deferred reference.
entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
entry.Value = value;
_effectiveValues[entryIndex.Index] = entry;
return entry;
}
}
else
{
// The value for this property was meant to come from a dictionary
// and the creation of that value had been deferred until this
// time for better performance. Now is the time to actually instantiate
// this value by querying it from the dictionary. Once we have the
// value we can actually replace the deferred reference marker
// with the actual value.
ModifiedValue modifiedValue = entry.ModifiedValue;
DeferredReference reference = null;
bool referenceFromExpression = false;
if (entry.IsCoercedWithCurrentValue)
{
if (!entry.IsAnimated)
{
reference = modifiedValue.CoercedValue as DeferredReference;
}
}
if (reference == null && entry.IsExpression)
{
if (!entry.IsAnimated && !entry.IsCoerced)
{
reference = (DeferredReference) modifiedValue.ExpressionValue;
referenceFromExpression = true;
}
}
Debug.Assert(reference != null, "the only modified values that can have deferredreferences are (a) expression, (b) coerced control value");
if (reference == null)
{
return effectiveEntry;
}
object value = reference.GetValue(entry.BaseValueSourceInternal);
if (!dp.IsValidValue(value))
{
throw new InvalidOperationException(SR.Format(SR.InvalidPropertyValue, value, dp.Name));
}
// Make sure the entryIndex is in sync after
// the inflation of the deferred reference.
entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
if (referenceFromExpression)
{
entry.SetExpressionValue(value, modifiedValue.BaseValue);
}
else
{
entry.SetCoercedValue(value, null, true /* skipBaseValueChecks */, entry.IsCoercedWithCurrentValue);
}
_effectiveValues[entryIndex.Index] = entry;
effectiveEntry.Value = value;
}
return effectiveEntry;
}
/// <summary>
/// Sets the local value of a property
/// </summary>
/// <param name="dp">Dependency property</param>
/// <param name="value">New local value</param>
public void SetValue(DependencyProperty dp, object value)
{
// Do not allow foreign threads access.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
this.VerifyAccess();
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
// Do standard property set
SetValueCommon(dp, value, metadata, false /* coerceWithDeferredReference */, false /* coerceWithCurrentValue */, OperationType.Unknown, false /* isInternal */);
}
/// <summary>
/// Sets the value of a property without changing its value source.
/// </summary>
/// <param name="dp">Dependency property</param>
/// <param name="value">New value</param>
/// <remarks>
/// This method is intended for use by a component that wants to
/// programmatically set the value of one of its own properties, in a
/// way that does not disable an application's declared use of that property.
/// SetCurrentValue changes the effective value of the property, but
/// existing triggers, data-binding, styles, etc. will continue to
/// work.
/// </remarks>
public void SetCurrentValue(DependencyProperty dp, object value)
{
// Do not allow foreign threads access.
// (This is a noop if this object is not assigned to a Dispatcher.)
this.VerifyAccess();
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
// Do standard property set
SetValueCommon(dp, value, metadata, false /* coerceWithDeferredReference */, true /* coerceWithCurrentValue */, OperationType.Unknown, false /* isInternal */);
}
/// <summary>
/// Sets the local value of a property
/// The purpose of this internal method is to reuse BooleanBoxes when setting boolean value
/// </summary>
/// <param name="dp">Dependency property</param>
/// <param name="value">New local value</param>
[FriendAccessAllowed] // Built into Base, also used by Core and Framework.
internal void SetValue(DependencyProperty dp, bool value)
{
SetValue(dp, MS.Internal.KnownBoxes.BooleanBoxes.Box(value));
}
/// <summary>
/// Sets the current value of a property
/// The purpose of this internal method is to reuse BooleanBoxes when setting boolean value
/// </summary>
/// <param name="dp">Dependency property</param>
/// <param name="value">New local value</param>
[FriendAccessAllowed] // Built into Base, also used by Core and Framework.
internal void SetCurrentValue(DependencyProperty dp, bool value)
{
SetCurrentValue(dp, MS.Internal.KnownBoxes.BooleanBoxes.Box(value));
}
/// <summary>
/// Internal version of SetValue that bypasses type check in IsValidValue;
/// This is used in property setters
/// </summary>
/// <param name="dp">Dependency property</param>
/// <param name="value">New local value</param>
[FriendAccessAllowed] // Built into Base, also used by Core and Framework.
internal void SetValueInternal(DependencyProperty dp, object value)
{
// Do not allow foreign threads access.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
this.VerifyAccess();
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
// Do standard property set
SetValueCommon(dp, value, metadata, false /* coerceWithDeferredReference */, false /* coerceWithCurrentValue */, OperationType.Unknown, true /* isInternal */);
}
/// <summary>
/// Internal version of SetCurrentValue that bypasses type check in IsValidValue;
/// This is used in property setters
/// </summary>
/// <param name="dp">Dependency property</param>
/// <param name="value">New local value</param>
[FriendAccessAllowed] // Built into Base, also used by Core and Framework.
internal void SetCurrentValueInternal(DependencyProperty dp, object value)
{
// Do not allow foreign threads access.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
this.VerifyAccess();
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
// Do standard property set
SetValueCommon(dp, value, metadata, false /* coerceWithDeferredReference */, true /* coerceWithCurrentValue */, OperationType.Unknown, true /* isInternal */);
}
/// <summary>
/// Sets the local value of a property.
/// </summary>
[FriendAccessAllowed] // Built into Base, also used by Framework.
internal void SetDeferredValue(DependencyProperty dp, DeferredReference deferredReference)
{
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
// Do standard property set
SetValueCommon(dp, deferredReference, metadata, true /* coerceWithDeferredReference */, false /* coerceWithCurrentValue */, OperationType.Unknown, false /* isInternal */);
}
/// <summary>
/// Sets the value of a property to a deferred reference, without changing the ValueSource.
/// </summary>
[FriendAccessAllowed] // Built into Base, also used by Framework.
internal void SetCurrentDeferredValue(DependencyProperty dp, DeferredReference deferredReference)
{
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
// Do standard property set
SetValueCommon(dp, deferredReference, metadata, true /* coerceWithDeferredReference */, true /* coerceWithCurrentValue */, OperationType.Unknown, false /* isInternal */);
}
/// <summary>
/// Sets the local value of a property with a mutable default value.
/// </summary>
[FriendAccessAllowed] // Built into Base, also used by Framework.
internal void SetMutableDefaultValue(DependencyProperty dp, object value)
{
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
// Do standard property set
SetValueCommon(dp, value, metadata, false /* coerceWithDeferredReference */, false /* coerceWithCurrentValue */, OperationType.ChangeMutableDefaultValue, false /* isInternal */);
}
/// <summary>
/// Sets the local value of a property
/// The purpose of this internal method is to reuse BooleanBoxes when setting boolean value
/// </summary>
/// <param name="dp">Dependency property key</param>
/// <param name="value">New local value</param>
[FriendAccessAllowed] // Built into Base, also used by Core and Framework.
internal void SetValue(DependencyPropertyKey dp, bool value)
{
SetValue(dp, MS.Internal.KnownBoxes.BooleanBoxes.Box(value));
}
/// <summary>
/// Sets the local value of a property
/// </summary>
public void SetValue(DependencyPropertyKey key, object value)
{
// Do not allow foreign threads access.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
this.VerifyAccess();
DependencyProperty dp;
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(key, out dp);
// Do standard property set
SetValueCommon(dp, value, metadata, false /* coerceWithDeferredReference */, false /* coerceWithCurrentValue */, OperationType.Unknown, false /* isInternal */);
}
/// <summary>
/// Called by SetValue or ClearValue to verify that the property
/// can be changed.
/// </summary>
private PropertyMetadata SetupPropertyChange(DependencyProperty dp)
{
if ( dp != null )
{
if ( !dp.ReadOnly )
{
// Get type-specific metadata for this property
return dp.GetMetadata(DependencyObjectType);
}
else
{
throw new InvalidOperationException(SR.Format(SR.ReadOnlyChangeNotAllowed, dp.Name));
}
}
else
{
throw new ArgumentNullException("dp");
}
}
/// <summary>
/// Called by SetValue or ClearValue to verify that the property
/// can be changed.
/// </summary>
private PropertyMetadata SetupPropertyChange(DependencyPropertyKey key, out DependencyProperty dp)
{
if ( key != null )
{
dp = key.DependencyProperty;
Debug.Assert(dp != null);
dp.VerifyReadOnlyKey(key);
// Get type-specific metadata for this property
return dp.GetMetadata(DependencyObjectType);
}
else
{
throw new ArgumentNullException("key");
}
}
/// <summary>
/// The common code shared by all variants of SetValue
/// </summary>
// Takes metadata from caller because most of them have already retrieved it
// for their own purposes, avoiding the duplicate GetMetadata call.
private void SetValueCommon(
DependencyProperty dp,
object value,
PropertyMetadata metadata,
bool coerceWithDeferredReference,
bool coerceWithCurrentValue,
OperationType operationType,
bool isInternal)
{
if (IsSealed)
{
throw new InvalidOperationException(SR.Format(SR.SetOnReadOnlyObjectNotAllowed, this));
}
Expression newExpr = null;
DependencySource[] newSources = null;
EntryIndex entryIndex = LookupEntry(dp.GlobalIndex);
// Treat Unset as a Clear
if( value == DependencyProperty.UnsetValue )
{
Debug.Assert(!coerceWithCurrentValue, "Don't call SetCurrentValue with UnsetValue");
// Parameters should have already been validated, so we call
// into the private method to avoid validating again.
ClearValueCommon(entryIndex, dp, metadata);
return;
}
// Validate the "value" against the DP.
bool isDeferredReference = false;
bool newValueHasExpressionMarker = (value == ExpressionInAlternativeStore);
// First try to validate the value; only after this validation fails should we
// do the more expensive checks (type checks) for the less common scenarios
if (!newValueHasExpressionMarker)
{
bool isValidValue = isInternal ? dp.IsValidValueInternal(value) : dp.IsValidValue(value);
// for properties of type "object", we have to always check for expression & deferredreference
if (!isValidValue || dp.IsObjectType)
{
// 2nd most common is expression
newExpr = value as Expression;
if (newExpr != null)
{
// For Expressions, perform additional validation
// Make sure Expression is "attachable"
if (!newExpr.Attachable)
{
throw new ArgumentException(SR.SharingNonSharableExpression);
}
// Check dispatchers of all Sources
// CALLBACK
newSources = newExpr.GetSources();
ValidateSources(this, newSources, newExpr);
}
else
{
// and least common is DeferredReference
isDeferredReference = (value is DeferredReference);
if (!isDeferredReference)
{
if (!isValidValue)
{
// it's not a valid value & it's not an expression, so throw
throw new ArgumentException(SR.Format(SR.InvalidPropertyValue, value, dp.Name));
}
}
}
}
}
// Get old value
EffectiveValueEntry oldEntry;
if (operationType == OperationType.ChangeMutableDefaultValue)
{
oldEntry = new EffectiveValueEntry(dp, BaseValueSourceInternal.Default);
oldEntry.Value = value;
}
else
{
oldEntry = GetValueEntry(entryIndex, dp, metadata, RequestFlags.RawEntry);
}
// if there's an expression in some other store, fetch it now
Expression currentExpr =
(oldEntry.HasExpressionMarker) ? _getExpressionCore(this, dp, metadata)
: (oldEntry.IsExpression) ? (oldEntry.LocalValue as Expression)
: null;
// Allow expression to store value if new value is
// not an Expression, if applicable
bool handled = false;
if ((currentExpr != null) && (newExpr == null))
{
// Resolve deferred references because we haven't modified
// the expression code to work with DeferredReference yet.
if (isDeferredReference)
{
value = ((DeferredReference) value).GetValue(BaseValueSourceInternal.Local);
}
// CALLBACK
handled = currentExpr.SetValue(this, dp, value);
entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
}
// Create the new effective value entry
EffectiveValueEntry newEntry;
if (handled)
{
// If expression handled set, then done
if (entryIndex.Found)
{
newEntry = _effectiveValues[entryIndex.Index];
}
else
{
// the expression.SetValue resulted in this value being removed from the table;
// use the default value.
newEntry = EffectiveValueEntry.CreateDefaultValueEntry(dp, metadata.GetDefaultValue(this, dp));
}
coerceWithCurrentValue = false; // expression already handled the control-value
}
else
{
// allow a control-value to coerce an expression value, when the
// expression didn't handle the value
if (coerceWithCurrentValue && currentExpr != null)
{
currentExpr = null;
}
newEntry = new EffectiveValueEntry(dp, BaseValueSourceInternal.Local);
// detach the old expression, if applicable
if (currentExpr != null)
{
// CALLBACK
DependencySource[] currentSources = currentExpr.GetSources();
UpdateSourceDependentLists(this, dp, currentSources, currentExpr, false); // Remove
// CALLBACK
currentExpr.OnDetach(this, dp);
currentExpr.MarkDetached();
entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
}
// attach the new expression, if applicable
if (newExpr == null)
{
// simple local value set
newEntry.HasExpressionMarker = newValueHasExpressionMarker;
newEntry.Value = value;
}
else
{
Debug.Assert(!coerceWithCurrentValue, "Expression values not supported in SetCurrentValue");
// First put the expression in the effectivevalueentry table for this object;
// this allows the expression to update the value accordingly in OnAttach
SetEffectiveValue(entryIndex, dp, dp.GlobalIndex, metadata, newExpr, BaseValueSourceInternal.Local);
// Before the expression is attached it has default value
object defaultValue = metadata.GetDefaultValue(this, dp);
entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
SetExpressionValue(entryIndex, defaultValue, newExpr);
UpdateSourceDependentLists(this, dp, newSources, newExpr, true); // Add
newExpr.MarkAttached();
// CALLBACK
newExpr.OnAttach(this, dp);
// the attach may have added entries in the effective value table ...
// so, update the entryIndex accordingly.
entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
newEntry = EvaluateExpression(
entryIndex,
dp,
newExpr,
metadata,
oldEntry,
_effectiveValues[entryIndex.Index]);
entryIndex = CheckEntryIndex(entryIndex, dp.GlobalIndex);
}
}
UpdateEffectiveValue(
entryIndex,
dp,
metadata,
oldEntry,
ref newEntry,
coerceWithDeferredReference,
coerceWithCurrentValue,
operationType);
}
//
// This is a helper routine to set this DO as the inheritance context of another,
// which has been set as a DP value here.
//
[FriendAccessAllowed] // Built into Base, also used by Core & Framework.
internal bool ProvideSelfAsInheritanceContext( object value, DependencyProperty dp )
{
DependencyObject doValue = value as DependencyObject;
if (doValue != null)
{
return ProvideSelfAsInheritanceContext(doValue, dp);
}
else
{
return false;
}
}
[FriendAccessAllowed] // Built into Base, also used by Core & Framework.
internal bool ProvideSelfAsInheritanceContext( DependencyObject doValue, DependencyProperty dp )
{
// We have to call Freezable.AddInheritanceContext even if the request
// for a new InheritanceContext is not allowed, because Freezable depends
// on side-effects from setting the "Freezable context". Freezable's
// implementation does its own checks of the conditions omitted here.
// Enhancement suggestion: Freezable should follow the same rules for
// InheritanceContext as everyone else
if (doValue != null &&
this.ShouldProvideInheritanceContext(doValue, dp) &&
(doValue is Freezable ||
(this.CanBeInheritanceContext &&
!doValue.IsInheritanceContextSealed)
))
{
DependencyObject oldInheritanceContext = doValue.InheritanceContext;
doValue.AddInheritanceContext(this, dp);
// return true if the inheritance context actually changed to the new value
return (this == doValue.InheritanceContext && this != oldInheritanceContext);
}
else
{
return false;
}
}
//
// This is a helper routine to remove this DO as the inheritance context of another.
//
[FriendAccessAllowed] // Built into Base, also used by Core & Framework.
internal bool RemoveSelfAsInheritanceContext( object value, DependencyProperty dp )
{
DependencyObject doValue = value as DependencyObject;
if (doValue != null)
{
return RemoveSelfAsInheritanceContext(doValue, dp);
}
else
{
return false;
}
}
[FriendAccessAllowed] // Built into Base, also used by Core & Framework.
internal bool RemoveSelfAsInheritanceContext( DependencyObject doValue, DependencyProperty dp )
{
// We have to call Freezable.RemoveInheritanceContext even if the request
// for a new InheritanceContext is not allowed, because Freezable depends
// on side-effects from setting the "Freezable context". Freezable's
// implementation does its own checks of the conditions omitted here.
// Enhancement suggestion: Freezable should follow the same rules for
// InheritanceContext as everyone else
if (doValue != null &&
this.ShouldProvideInheritanceContext(doValue, dp) &&
(doValue is Freezable ||
(this.CanBeInheritanceContext &&
!doValue.IsInheritanceContextSealed)
))
{
DependencyObject oldInheritanceContext = doValue.InheritanceContext;
doValue.RemoveInheritanceContext(this, dp);
// return true if the inheritance context actually changed to the new value
return (this == oldInheritanceContext && doValue.InheritanceContext != oldInheritanceContext);
}
else
{
return false;
}
}
/// <summary>
/// Clears the local value of a property
/// </summary>
/// <param name="dp">Dependency property</param>
public void ClearValue(DependencyProperty dp)
{
// Do not allow foreign threads to clear properties.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
this.VerifyAccess();
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(dp);
EntryIndex entryIndex = LookupEntry(dp.GlobalIndex);
ClearValueCommon(entryIndex, dp, metadata);
}
/// <summary>
/// Clears the local value of a property
/// </summary>
public void ClearValue(DependencyPropertyKey key)
{
// Do not allow foreign threads to clear properties.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
this.VerifyAccess();
DependencyProperty dp;
// Cache the metadata object this method needed to get anyway.
PropertyMetadata metadata = SetupPropertyChange(key, out dp);
EntryIndex entryIndex = LookupEntry(dp.GlobalIndex);
ClearValueCommon(entryIndex, dp, metadata);
}
/// <summary>
/// The common code shared by all variants of ClearValue
/// </summary>
private void ClearValueCommon(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata)
{
if (IsSealed)
{
throw new InvalidOperationException(SR.Format(SR.ClearOnReadOnlyObjectNotAllowed, this));
}
// Get old value
EffectiveValueEntry oldEntry = GetValueEntry(
entryIndex,