-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
FrameworkElement.cs
6566 lines (5650 loc) · 274 KB
/
FrameworkElement.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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Threading;
using System.Threading;
using System.Reflection;
using System.Windows.Data;
using System.Windows.Diagnostics;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Markup;
using System.Windows.Controls;
using System.Windows.Automation;
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.PresentationFramework; // SafeSecurityHelper
using MS.Utility;
using MS.Internal.Automation;
using MS.Internal.PtsTable; // BodyContainerProxy
using System.Security;
// Disabling 1634 and 1691:
// In order to avoid generating warnings about unknown message numbers and
// unknown pragmas when compiling C# source code with the C# compiler,
// you need to disable warnings 1634 and 1691. (Presharp Documentation)
#pragma warning disable 1634, 1691
namespace System.Windows
{
/// <summary>
/// HorizontalAlignment - The HorizontalAlignment enum is used to describe
/// how element is positioned or stretched horizontally within a parent's layout slot.
/// </summary>
[Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)]
public enum HorizontalAlignment
{
/// <summary>
/// Left - Align element towards the left of a parent's layout slot.
/// </summary>
Left = 0,
/// <summary>
/// Center - Center element horizontally.
/// </summary>
Center = 1,
/// <summary>
/// Right - Align element towards the right of a parent's layout slot.
/// </summary>
Right = 2,
/// <summary>
/// Stretch - Stretch element horizontally within a parent's layout slot.
/// </summary>
Stretch = 3,
}
/// <summary>
/// VerticalAlignment - The VerticalAlignment enum is used to describe
/// how element is positioned or stretched vertically within a parent's layout slot.
/// </summary>
[Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)]
public enum VerticalAlignment
{
/// <summary>
/// Top - Align element towards the top of a parent's layout slot.
/// </summary>
Top = 0,
/// <summary>
/// Center - Center element vertically.
/// </summary>
Center = 1,
/// <summary>
/// Bottom - Align element towards the bottom of a parent's layout slot.
/// </summary>
Bottom = 2,
/// <summary>
/// Stretch - Stretch element vertically within a parent's layout slot.
/// </summary>
Stretch = 3,
}
/// <summary>
/// The base object for the Frameworks
/// </summary>
/// <remarks>
/// FrameworkElement is the interface between higher-level Framework
/// classes and PresentationCore services
/// </remarks>
[StyleTypedProperty(Property = "FocusVisualStyle", StyleTargetType = typeof(Control))]
[XmlLangProperty("Language")]
[UsableDuringInitialization(true)]
public partial class FrameworkElement : UIElement, IFrameworkInputElement, ISupportInitialize, IHaveResources, IQueryAmbient
{
static private readonly Type _typeofThis = typeof(FrameworkElement);
/// <summary>
/// Default FrameworkElement constructor
/// </summary>
/// <remarks>
/// Automatic determination of current Dispatcher. Use alternative constructor
/// that accepts a Dispatcher for best performance.
/// </remarks>
public FrameworkElement() : base()
{
// Initialize the _styleCache to the default value for StyleProperty.
// If the default value is non-null then wire it to the current instance.
PropertyMetadata metadata = StyleProperty.GetMetadata(DependencyObjectType);
Style defaultValue = (Style) metadata.DefaultValue;
if (defaultValue != null)
{
OnStyleChanged(this, new DependencyPropertyChangedEventArgs(StyleProperty, metadata, null, defaultValue));
}
if (((FlowDirection)FlowDirectionProperty.GetDefaultValue(DependencyObjectType)) == FlowDirection.RightToLeft)
{
IsRightToLeft = true;
}
// Set the ShouldLookupImplicitStyles flag to true if App.Resources has implicit styles.
Application app = Application.Current;
if (app != null && app.HasImplicitStylesInResources)
{
ShouldLookupImplicitStyles = true;
}
FrameworkElement.EnsureFrameworkServices();
}
/// <summary>Style Dependency Property</summary>
[CommonDependencyProperty]
public static readonly DependencyProperty StyleProperty =
DependencyProperty.Register(
"Style",
typeof(Style),
_typeofThis,
new FrameworkPropertyMetadata(
(Style) null, // default value
FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnStyleChanged)));
/// <summary>
/// Style property
/// </summary>
public Style Style
{
get { return _styleCache; }
set { SetValue(StyleProperty, value); }
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeStyle()
{
return !IsStyleSetFromGenerator
&& ReadLocalValue(StyleProperty) != DependencyProperty.UnsetValue;
}
// Invoked when the Style property is changed
private static void OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement fe = (FrameworkElement) d;
fe.HasLocalStyle = (e.NewEntry.BaseValueSourceInternal == BaseValueSourceInternal.Local);
StyleHelper.UpdateStyleCache(fe, null, (Style) e.OldValue, (Style) e.NewValue, ref fe._styleCache);
}
/// <summary>
/// OverridesDefaultStyleProperty
/// </summary>
public static readonly DependencyProperty OverridesDefaultStyleProperty
= DependencyProperty.Register("OverridesDefaultStyle", typeof(bool), _typeofThis,
new FrameworkPropertyMetadata(
BooleanBoxes.FalseBox, // default value
FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnThemeStyleKeyChanged)));
/// <summary>
/// This specifies that the current style ignores all
/// properties from the Theme Style
/// </summary>
public bool OverridesDefaultStyle
{
get { return (bool)GetValue(OverridesDefaultStyleProperty); }
set { SetValue(OverridesDefaultStyleProperty, BooleanBoxes.Box(value)); }
}
/// The UseLayoutRounding property.
/// </summary>
public static readonly DependencyProperty UseLayoutRoundingProperty =
DependencyProperty.Register(
"UseLayoutRounding",
typeof(bool),
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnUseLayoutRoundingChanged)
));
/// <summary>
/// Gets or sets a value indicating whether layout rounding should be applied to this element's size and position during
/// Measure and Arrange so that it aligns to pixel boundaries. This property is inherited by children.
/// </summary>
public bool UseLayoutRounding
{
get { return (bool)GetValue(UseLayoutRoundingProperty); }
set { SetValue(UseLayoutRoundingProperty, BooleanBoxes.Box(value)); }
}
private static void OnUseLayoutRoundingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement fe = (FrameworkElement)d;
bool newValue = (bool)e.NewValue;
fe.SetFlags(newValue, VisualFlags.UseLayoutRounding);
}
/// <summary>
/// DefaultStyleKeyProperty
/// </summary>
protected internal static readonly DependencyProperty DefaultStyleKeyProperty
= DependencyProperty.Register("DefaultStyleKey", typeof(object), _typeofThis,
new FrameworkPropertyMetadata(
null, // default value
FrameworkPropertyMetadataOptions.AffectsMeasure,
new PropertyChangedCallback(OnThemeStyleKeyChanged)));
/// <summary>
/// This specifies the key to use to find
/// a style in a theme for this control
/// </summary>
protected internal object DefaultStyleKey
{
get { return GetValue(DefaultStyleKeyProperty); }
set { SetValue(DefaultStyleKeyProperty, value); }
}
// This function is called when ThemeStyleKey or OverridesThemeStyle properties change
private static void OnThemeStyleKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Re-evaluate ThemeStyle because it is
// a factor of the ThemeStyleKey property
((FrameworkElement)d).UpdateThemeStyleProperty();
}
// Cache the ThemeStyle for the current instance if there is a DefaultStyleKey specified for it
internal Style ThemeStyle
{
get { return _themeStyleCache; }
}
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal virtual DependencyObjectType DTypeThemeStyleKey
{
get { return null; }
}
// Invoked when the ThemeStyle property is changed
internal static void OnThemeStyleChanged(DependencyObject d, object oldValue, object newValue)
{
FrameworkElement fe = (FrameworkElement) d;
StyleHelper.UpdateThemeStyleCache(fe, null, (Style) oldValue, (Style) newValue, ref fe._themeStyleCache);
}
// Internal helper so the FrameworkElement could see the
// ControlTemplate/DataTemplate set on the
// Control/Page/PageFunction/ContentPresenter
internal virtual FrameworkTemplate TemplateInternal
{
get { return null; }
}
// Internal helper so the FrameworkElement could see the
// ControlTemplate/DataTemplate set on the
// Control/Page/PageFunction/ContentPresenter
internal virtual FrameworkTemplate TemplateCache
{
get { return null; }
set {}
}
// Internal so that StyleHelper could uniformly call the TemplateChanged
// virtual on any templated parent
internal virtual void OnTemplateChangedInternal(
FrameworkTemplate oldTemplate,
FrameworkTemplate newTemplate)
{
HasTemplateChanged = true;
}
/// <summary>
/// Style has changed
/// </summary>
/// <param name="oldStyle">The old Style</param>
/// <param name="newStyle">The new Style</param>
protected internal virtual void OnStyleChanged(Style oldStyle, Style newStyle)
{
HasStyleChanged = true;
}
/// <summary>
/// This method is called from during property invalidation time. If the FrameworkElement has a child on which
/// some property was invalidated and the property was marked as AffectsParentMeasure or AffectsParentArrange
/// during registration, this method is invoked to let a FrameworkElement know which particualr child must be
/// remeasured if the FrameworkElement wants to do partial (incremental) update of layout.
/// <para/>
/// Olny advanced FrameworkElement, which implement incremental update should override this method. Since
/// Panel always gets InvalidateMeasure or InvalidateArrange called in this situation, it ensures that
/// the FrameworkElement will be re-measured and/or re-arranged. Only if the FrameworkElement wants to implement a performance
/// optimization and avoid calling Measure/Arrange on all children, it should override this method and
/// store the info about invalidated children, to use subsequently in the FrameworkElement's MeasureOverride/ArrangeOverride
/// implementations.
/// <para/>
/// Note: to listen for added/removed children, Panel should provide its derived version of
/// <see cref="UIElementCollection"/>.
/// </summary>
///<param name="child">Reference to a child UIElement that had AffectsParentMeasure/AffectsParentArrange property invalidated.</param>
protected internal virtual void ParentLayoutInvalidated(UIElement child)
{
}
/// <summary>
/// ApplyTemplate is called on every Measure
/// </summary>
/// <remarks>
/// Used by subclassers as a notification to delay fault-in their Visuals
/// Used by application authors ensure an Elements Visual tree is completely built
/// </remarks>
/// <returns>Whether Visuals were added to the tree</returns>
public bool ApplyTemplate()
{
// Notify the ContentPresenter/ItemsPresenter that we are about to generate the
// template tree and allow them to choose the right template to be applied.
OnPreApplyTemplate();
bool visualsCreated = false;
UncommonField<HybridDictionary[]> dataField = StyleHelper.TemplateDataField;
FrameworkTemplate template = TemplateInternal;
// The Template may change in OnApplyTemplate so we'll retry in this case.
// We dont want to get stuck in a loop doing this, so limit the number of
// template changes before we bail out.
int retryCount = 2;
for (int i = 0; template != null && i < retryCount; i++)
{
// VisualTree application never clears existing trees. Trees
// will be conditionally cleared on Template invalidation
if (!HasTemplateGeneratedSubTree)
{
// Create a VisualTree using the given template
visualsCreated = template.ApplyTemplateContent(dataField, this);
if (visualsCreated)
{
// This VisualTree was created via a Template
HasTemplateGeneratedSubTree = true;
// We may have had trigger actions that had to wait until the
// template subtree has been created. Invoke them now.
StyleHelper.InvokeDeferredActions(this, template);
// Notify sub-classes when the template tree has been created
OnApplyTemplate();
}
if (template != TemplateInternal)
{
template = TemplateInternal;
continue;
}
}
break;
}
OnPostApplyTemplate();
return visualsCreated;
}
/// <summary>
/// This virtual is called by FE.ApplyTemplate before it does work to generate the template tree.
/// </summary>
/// <remarks>
/// This virtual is overridden for the following three reasons
/// 1. By ContentPresenter/ItemsPresenter to choose the template to be applied in this case.
/// 2. By RowPresenter/ColumnHeaderPresenter/InkCanvas to build custom visual trees
/// 3. By ScrollViewer/TickBar/ToolBarPanel/Track to hookup bindings to their TemplateParent
/// </remarks>
internal virtual void OnPreApplyTemplate()
{
}
/// <summary>
/// This is the virtual that sub-classes must override if they wish to get
/// notified that the template tree has been created.
/// </summary>
/// <remarks>
/// This virtual is called after the template tree has been generated and it is invoked only
/// if the call to ApplyTemplate actually caused the template tree to be generated.
/// </remarks>
public virtual void OnApplyTemplate()
{
}
/// <summary>
/// This virtual is called by FE.ApplyTemplate after it generates the template tree.
/// </summary>
/// <remarks>
/// This is overrideen by Control to update the visual states
/// </remarks>
internal virtual void OnPostApplyTemplate()
{
}
/// <summary>
/// Begins the given Storyboard as a non-controllable Storyboard and
/// the default handoff policy.
/// </summary>
public void BeginStoryboard(Storyboard storyboard)
{
BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, false);
}
/// <summary>
/// Begins the given Storyboard as a non-controllable Storyboard but
/// with the given handoff policy.
/// </summary>
public void BeginStoryboard(Storyboard storyboard, HandoffBehavior handoffBehavior)
{
BeginStoryboard(storyboard, handoffBehavior, false);
}
/// <summary>
/// Begins the given Storyboard as a Storyboard with the given handoff
/// policy, and with the specified state for controllability.
/// </summary>
public void BeginStoryboard(Storyboard storyboard, HandoffBehavior handoffBehavior, bool isControllable)
{
ArgumentNullException.ThrowIfNull(storyboard);
// Storyboard.Begin is a public API and needs to be validating handoffBehavior anyway.
storyboard.Begin( this, handoffBehavior, isControllable );
}
// Given a FrameworkElement and a name string, this routine will try to find
// a node with Name property set to the given name. It will search all
// the child logical tree nodes of the given starting element.
// If the name string is null or an empty string, the given starting element
// is returned.
// If the name is found on a FrameworkContentElement, an exception is thrown
// If the name is not found attached to anything, an exception is thrown
internal static FrameworkElement FindNamedFrameworkElement( FrameworkElement startElement, string targetName )
{
FrameworkElement targetFE = null;
if( targetName == null || targetName.Length == 0 )
{
targetFE = startElement;
}
else
{
DependencyObject targetObject = null;
targetObject = LogicalTreeHelper.FindLogicalNode( startElement, targetName );
if( targetObject == null )
{
throw new ArgumentException( SR.Format(SR.TargetNameNotFound, targetName));
}
FrameworkObject fo = new FrameworkObject(targetObject);
if( fo.IsFE )
{
targetFE = fo.FE;
}
else
{
throw new InvalidOperationException(SR.Format(SR.NamedObjectMustBeFrameworkElement, targetName));
}
}
return targetFE;
}
/// <summary>
/// Triggers associated with this object. Both the triggering condition
/// and the trigger effect may be on this object or on its tree child
/// objects.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TriggerCollection Triggers
{
get
{
TriggerCollection triggerCollection = EventTrigger.TriggerCollectionField.GetValue(this);
if (triggerCollection == null)
{
// Give the TriggerCollectiona back-link so that it can update
// 'this' on Add/Remove.
triggerCollection = new TriggerCollection(this);
EventTrigger.TriggerCollectionField.SetValue(this, triggerCollection);
}
return triggerCollection;
}
}
/// <summary>
/// Return true if the Triggers property contains something that
/// should be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeTriggers()
{
TriggerCollection triggerCollection = EventTrigger.TriggerCollectionField.GetValue(this);
if (triggerCollection == null || triggerCollection.Count == 0)
{
return false;
}
return true;
}
// This should be called when the FrameworkElement tree is built up,
// at this point we can process all the setter-related information
// because now we'll be able to resolve "Target" references in setters.
private void PrivateInitialized()
{
// Process Trigger information when this object is loaded.
EventTrigger.ProcessTriggerCollection(this);
}
/// <summary>
/// Reference to the style parent of this node, if any.
/// </summary>
/// <returns>
/// Reference to FrameworkElement or FrameworkContentElement
/// whose Template.VisualTree caused this element to be created,
/// null if this does not apply.
/// </returns>
public DependencyObject TemplatedParent
{
get
{
return _templatedParent;
}
}
/// <summary>
/// Returns true if this FrameworkElement was created as the root
/// node of a Template.VisualTree or if it were the root node of a template.
/// </summary>
// Most people can get this information by comparing this.TemplatedParent
// against this.Parent. However, layout has a need to know this when
// the tree is not yet hooked up and/or just disconnected.
// This function uses esoteric knowledge of FrameworkElementFactory
// and how it is actually used to build visual trees from style.
// Exposing this property is easier than explaining the ChildIndex magic.
internal bool IsTemplateRoot
{
get
{
return (TemplateChildIndex==1);
}
}
/// <summary>
/// Gets or sets the template child of the FrameworkElement.
/// </summary>
virtual internal UIElement TemplateChild
{
get
{
return _templateChild;
}
set
{
if (value != _templateChild)
{
RemoveVisualChild(_templateChild);
_templateChild = value;
AddVisualChild(value);
}
}
}
/// <summary>
/// Gets the element that should be used as the StateGroupRoot for VisualStateMangager.GoToState calls
/// </summary>
internal virtual FrameworkElement StateGroupsRoot
{
get
{
return _templateChild as FrameworkElement;
}
}
/// <summary>
/// Gets the number of Visual children of this FrameworkElement.
/// </summary>
/// <remarks>
/// Derived classes override this property getter to provide the children count
/// of their custom children collection.
/// </remarks>
protected override int VisualChildrenCount
{
get
{
return (_templateChild == null) ? 0 : 1;
}
}
/// <summary>
/// Gets the Visual child at the specified index.
/// </summary>
/// <remarks>
/// Derived classes that provide a custom children collection must override this method
/// and return the child at the specified index.
/// </remarks>
protected override Visual GetVisualChild(int index)
{
if (_templateChild == null)
{
throw new ArgumentOutOfRangeException("index", index, SR.Visual_ArgumentOutOfRange);
}
if (index != 0)
{
throw new ArgumentOutOfRangeException("index", index, SR.Visual_ArgumentOutOfRange);
}
return _templateChild;
}
/// <summary>
/// Check if resource is not empty.
/// Call HasResources before accessing resources every time you need
/// to query for a resource.
/// </summary>
internal bool HasResources
{
get
{
ResourceDictionary resources = ResourcesField.GetValue(this);
return (resources != null &&
((resources.Count > 0) || (resources.MergedDictionaries.Count > 0)));
}
}
/// <summary>
/// Current locally defined Resources
/// </summary>
[Ambient]
public ResourceDictionary Resources
{
get
{
ResourceDictionary resources = ResourcesField.GetValue(this);
if (resources == null)
{
resources = new ResourceDictionary();
resources.AddOwner(this);
ResourcesField.SetValue(this, resources);
if( TraceResourceDictionary.IsEnabled )
{
TraceResourceDictionary.TraceActivityItem(
TraceResourceDictionary.NewResourceDictionary,
this,
0,
resources );
}
}
return resources;
}
set
{
ResourceDictionary oldValue = ResourcesField.GetValue(this);
ResourcesField.SetValue(this, value);
if( TraceResourceDictionary.IsEnabled )
{
TraceResourceDictionary.Trace(
TraceEventType.Start,
TraceResourceDictionary.NewResourceDictionary,
this,
oldValue,
value );
}
if (oldValue != null)
{
// This element is no longer an owner for the old RD
oldValue.RemoveOwner(this);
}
if (value != null)
{
if (!value.ContainsOwner(this))
{
// This element is an owner for the new RD
value.AddOwner(this);
}
}
// Invalidate ResourceReference properties for this subtree
// Invalidating only when not empty will not take care of the case where
// a RD is not sealed, and its entire contents are cleared. This needs to be handled with
// notifications from the RD. But this is not that bad as Sealing it will cause the
// final invalidation & it is no worse than the old code that also did not invalidate in this case
// Removed the not-empty check to allow invalidations in the case that the old dictionary
// is replaced with a new empty dictionary
if (oldValue != value)
{
TreeWalkHelper.InvalidateOnResourcesChange(this, null, new ResourcesChangeInfo(oldValue, value));
}
if( TraceResourceDictionary.IsEnabled )
{
TraceResourceDictionary.Trace(
TraceEventType.Stop,
TraceResourceDictionary.NewResourceDictionary,
this,
oldValue,
value );
}
}
}
ResourceDictionary IHaveResources.Resources
{
get { return Resources; }
set { Resources = value; }
}
bool IQueryAmbient.IsAmbientPropertyAvailable(string propertyName)
{
// We want to make sure that StaticResource resolution checks the .Resources
// Ie. The Ambient search should look at Resources if it is set.
// Even if it wasn't set from XAML (eg. the Ctor (or derived Ctor) added stuff)
return (propertyName != "Resources" || HasResources);
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
// This is to tell the serialization engine when we
// must and must not serialize the Resources property
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeResources()
{
if (Resources == null || Resources.Count == 0)
{
return false;
}
return true;
}
/// <summary>
/// Retrieves the element in the VisualTree of thie element that corresponds to
/// the element with the given childName in this element's style definition
/// </summary>
/// <param name="childName">the Name to find the matching element for</param>
/// <returns>The Named element. Null if no element has this Name.</returns>
protected internal DependencyObject GetTemplateChild(string childName)
{
FrameworkTemplate template = TemplateInternal;
/* Calling this before getting a style/template is not a bug.
Debug.Assert(template != null,
"The VisualTree should have been created from a Template");
*/
if (template == null)
{
return null;
}
return StyleHelper.FindNameInTemplateContent(this, childName, template) as DependencyObject;
}
/// <summary>
/// Searches for a resource with the passed resourceKey and returns it.
/// Throws an exception if the resource was not found.
/// </summary>
/// <remarks>
/// If the sources is not found on the called Element, the parent
/// chain is searched, using the logical tree.
/// </remarks>
/// <param name="resourceKey">Name of the resource</param>
/// <returns>The found resource.</returns>
public object FindResource(object resourceKey)
{
// Verify Context Access
// VerifyAccess();
ArgumentNullException.ThrowIfNull(resourceKey);
object resource = FrameworkElement.FindResourceInternal(this, null /* fce */, resourceKey);
if (resource == DependencyProperty.UnsetValue)
{
// Resource not found in parent chain, app or system
Helper.ResourceFailureThrow(resourceKey);
}
return resource;
}
/// <summary>
/// Searches for a resource with the passed resourceKey and returns it
/// </summary>
/// <remarks>
/// If the sources is not found on the called Element, the parent
/// chain is searched, using the logical tree.
/// </remarks>
/// <param name="resourceKey">Name of the resource</param>
/// <returns>The found resource. Null if not found.</returns>
public object TryFindResource(object resourceKey)
{
// Verify Context Access
// VerifyAccess();
ArgumentNullException.ThrowIfNull(resourceKey);
object resource = FrameworkElement.FindResourceInternal(this, null /* fce */, resourceKey);
if (resource == DependencyProperty.UnsetValue)
{
// Resource not found in parent chain, app or system
// This is where we translate DependencyProperty.UnsetValue to a null
resource = null;
}
return resource;
}
// FindImplicitSytle(fe) : Default: unlinkedParent, deferReference
internal static object FindImplicitStyleResource(FrameworkElement fe, object resourceKey, out object source)
{
// Do a FindResource call only if someone in the ancestry has
// implicit styles. This is a performance optimization.
if (fe.ShouldLookupImplicitStyles)
{
object unlinkedParent = null;
bool allowDeferredResourceReference = false;
bool mustReturnDeferredResourceReference = false;
// Implicit style lookup must stop at the app.
bool isImplicitStyleLookup = true;
// For non-controls the implicit StyleResource lookup must stop at
// the templated parent. Look at task 25606 for further details.
DependencyObject boundaryElement = null;
if (!(fe is Control))
{
boundaryElement = fe.TemplatedParent;
}
object implicitStyle = FindResourceInternal(fe,
null, // fce
FrameworkElement.StyleProperty, // dp
resourceKey,
unlinkedParent,
allowDeferredResourceReference,
mustReturnDeferredResourceReference,
boundaryElement,
isImplicitStyleLookup,
out source);
// The reason this assert is commented is because there are specific scenarios when we can reach
// here even before the ShouldLookupImplicitStyles flag is updated. But this is still acceptable
// because the flag does get updated and the style property gets re-fetched soon after.
// Look at AccessText.GetVisualChild implementation for example and
// consider the following sequence of operations.
// 1. contentPresenter.AddVisualChild(accessText)
// 1.1. accessText._parent = contentPresenter
// 1.2. accessText.GetVisualChild(...)
// 1.2.1 accessText.AddVisualChild(textBlock)
// 1.2.1.1 textBlock.OnVisualParentChanged()
// 1.2.1.1.1 FindImplicitStyleResource(textBlock)
// .
// .
// .
// 1.3 accessText.OnVisualParentChanged
// 1.3.1 Set accessText.ShouldLookupImplicitStyle
// 1.3.2 FindImplicitStyleResource(accessText)
// 1.3.3 Set textBlock.ShouldLookupImplicitStyle
// 1.3.4 FindImplicitStyleResource(textBlock)
// Notice how we end up calling FindImplicitStyleResource on the textBlock before we have set the
// ShouldLookupImplicitStyle flag on either accessText or textBlock. However this is still acceptable
// because we eventually going to synchronize the flag and the style property value on both these objects.
// Debug.Assert(!(implicitStyle != DependencyProperty.UnsetValue && fe.ShouldLookupImplicitStyles == false),
// "ShouldLookupImplicitStyles is false even while there exists an implicit style in the lookup path. To be precise at source " + source);
return implicitStyle;
}
source = null;
return DependencyProperty.UnsetValue;
}
// FindImplicitSytle(fce) : Default: unlinkedParent, deferReference
internal static object FindImplicitStyleResource(FrameworkContentElement fce, object resourceKey, out object source)
{
// Do a FindResource call only if someone in the ancestry has
// implicit styles. This is a performance optimization.
if (fce.ShouldLookupImplicitStyles)
{
object unlinkedParent = null;
bool allowDeferredResourceReference = false;
bool mustReturnDeferredResourceReference = false;
// Implicit style lookup must stop at the app.
bool isImplicitStyleLookup = true;
// For non-controls the implicit StyleResource lookup must stop at
// the templated parent. Look at task 25606 for further details.
DependencyObject boundaryElement = fce.TemplatedParent;
object implicitStyle = FindResourceInternal(null, fce, FrameworkContentElement.StyleProperty, resourceKey, unlinkedParent, allowDeferredResourceReference, mustReturnDeferredResourceReference, boundaryElement, isImplicitStyleLookup, out source);
// Look at comments on the FE version of this method.
// Debug.Assert(!(implicitStyle != DependencyProperty.UnsetValue && fce.ShouldLookupImplicitStyles == false),
// "ShouldLookupImplicitStyles is false even while there exists an implicit style in the lookup path. To be precise at source " + source);
return implicitStyle;
}
source = null;
return DependencyProperty.UnsetValue;
}
// Internal method for Parser to find a resource when
// the instance is not yet hooked to the logical tree
// This method returns DependencyProperty.UnsetValue when
// resource is not found. Otherwise it returns the value
// found. NOTE: Value resource found could be null
// FindResource(fe/fce) Default: dp, unlinkedParent, deferReference, boundaryElement, source, isImplicitStyleLookup
internal static object FindResourceInternal(FrameworkElement fe, FrameworkContentElement fce, object resourceKey)
{
object source;
return FindResourceInternal(fe,
fce,
null, // dp,
resourceKey,
null, // unlinkedParent,
false, // allowDeferredResourceReference,
false, // mustReturnDeferredResourceReference,
null, // boundaryElement,
false, // isImplicitStyleLookup,
out source);
}