Remarks

FrameworkElement is a base element: it's a class that many other Windows Runtime classes inherit from in order to support the XAML UI element model. Properties, methods and events that FrameworkElement defines are inherited by hundreds of other Windows Runtime classes.

Many common XAML UI classes derive from FrameworkElement, either directly or through intermediate base classes such as Panel or Control. Typically, you don't derive classes directly from FrameworkElement, because certain expected services for a class that is intended for a UI representation (such as template support) are not fully implemented there. More commonly used base classes for derived custom classes are:

FrameworkElement API and features

FrameworkElement extends UIElement, which is another base element, and adds support for various Windows Runtime feature areas.

Layout

The layout system recognizes all objects that derive from FrameworkElement to be elements that potentially participate in layout and should have a display area in the app UI. The layout system reads various properties that are defined at FrameworkElement level, such as MinWidth. Most UI elements use the FrameworkElement -defined Width and Height for their basic sizing information. FrameworkElement provides extensible methods for specialized layout behavior that panels and controls with content can override in their class implementations. For more info, see Define layouts with XAML.

Object lifetime events

You often want to know when an object is first loaded (loaded is defined as when an object becomes attached to an object tree that connects to the root visual). FrameworkElement defines events related to object lifetime that provide useful hooks for code-behind operations. For example you need object lifetime info to add child objects to a collection or set properties on child objects just prior to use, with assurance that the necessary objects in the object tree have already been instantiated from XAML markup. For more info, see Events and routed events overview.

XAML language and programming model integration

Usually your app's element structure resembles the XAML markup that you defined to create the UI, but sometimes that structure changes after the XAML was parsed. FrameworkElement defines the Name property and related API, which are useful for finding elements and element relationships at run-time. For more info, see XAML namescopes.

FrameworkElement dependency properties

Many of the read-write properties of the FrameworkElement base element class are dependency properties. Dependency properties support some of the basic programming model features for a UWP app using C++, C#, or Visual Basic, such as styles and templates, data binding, XAML resource references, and property-changed logic. For more info on dependency properties and the features they support, see Dependency properties overview.

FrameworkElement derived classes

FrameworkElement is the parent class for several immediately derived classes that distinguish several broad classifications of UI elements. Here are some of the notable derived classes:

Control: Control has many more derived control classes, basically all of the XAML controls that you use for a Windows Runtime UI are derived from Control.

The height, in pixels, of the object. The default is 0. The default might be encountered if the object has not been loaded and hasn't yet been involved in a layout pass that renders the UI.

Examples

This example shows a common scenario where you use the ActualHeight of one or more elements in UI to set the Height of either one of the involved elements or a different element, so that the same net height is maintained after the action. This is usually done in response to event handlers that are invoked when elements are opened or closed, or the display area changes.

void SDKSample::WebViewControl::PageWithAppBar::BottomAppBar_Opened(Object^ sender, Object^ obj)
{
// AppBar has Opened so we need to put the WebView back to its
// original size/location.
AppBar^ bottomAppBar = (AppBar^) sender;
if (bottomAppBar != nullptr)
{
// Force layout so that we can guarantee that our AppBar's
// actual height has height
this->UpdateLayout();
// Get the height of the AppBar
double appBarHeight = bottomAppBar->ActualHeight;
// Reduce the height of the WebView to allow for the AppBar
WebView8->Height = WebView8->ActualHeight - appBarHeight;
// Translate the WebView in the Y direction to reclaim the space occupied by the AppBar.
TranslateYOpen->To = -appBarHeight / 2.0;
// Run our translate animation to match the AppBar
OpenAppBar->Begin();
}
}

void BottomAppBar_Opened(object sender, object e)
{
// AppBar has Opened so we need to put the WebView back to its
// original size/location.
AppBar bottomAppBar = sender as AppBar;
if (bottomAppBar != null)
{
// Force layout so that we can guarantee that our AppBar's
// actual height has height
this.UpdateLayout();
// Get the height of the AppBar
double appBarHeight = bottomAppBar.ActualHeight;
// Reduce the height of the WebView to allow for the AppBar
WebView8.Height = WebView8.ActualHeight - appBarHeight;
// Translate the WebView in the Y direction to reclaim the space occupied by
// the AppBar. Notice that we translate it by appBarHeight / 2.0.
// This is because the WebView has VerticalAlignment and HorizontalAlignment
// of 'Stretch' and when we reduce its size it reduces its overall size
// from top and bottom by half the amount.
TranslateYOpen.To = -appBarHeight / 2.0;
// Run our translate animation to match the AppBar
OpenAppBar.Begin();
}
}

Private Sub BottomAppBar_Opened(sender As Object, e As Object)
' AppBar has Opened so we need to put the WebView back to its
' original size/location.
Dim bottomAppBar As AppBar = TryCast(sender, AppBar)
If bottomAppBar IsNot Nothing Then
' Force layout so that we can guarantee that our AppBar's
' actual height has height
Me.UpdateLayout()
' Get the height of the AppBar
Dim appBarHeight As Double = bottomAppBar.ActualHeight
' Reduce the height of the WebView to allow for the AppBar
WebView8.Height = WebView8.ActualHeight - appBarHeight
' Translate the WebView in the Y direction to reclaim the space occupied by
' the AppBar. Notice that we translate it by appBarHeight / 2.0.
' This is because the WebView has VerticalAlignment and HorizontalAlignment
' of 'Stretch' and when we reduce its size it reduces its overall size
' from top and bottom by half the amount.
TranslateYOpen.[To] = -appBarHeight / 2.0
' Run our translate animation to match the AppBar
OpenAppBar.Begin()
End If
End Sub

Remarks

Note

Although it has an ActualHeightProperty backing field, ActualHeight does not raise property change notifications and it should be thought of as a regular CLR property and not a dependency property.

ActualHeight is a calculated property. The calculations are a result of a layout pass, where the object is sized in layout according to the logic of its successive layout parents. For more info see Define layouts with XAML.

ActualHeight can have multiple or incremental reported changes to the value because of operations by the layout system. If you get the value while layout is still iterating, the layout system might still be calculating the required measure of space for child objects, constraints by the parent object, and so on. Because the value is based on an actual rendering pass, it may lag slightly behind the set value of properties like Height, which can be the basis of the input change.

The width, in pixels, of the object. The default is 0. The default might be encountered if the object has not been loaded and hasn't yet been involved in a layout pass that renders the UI.

Remarks

Note

Although it has an ActualWidthProperty backing field, ActualWidth does not raise property change notifications and it should be thought of as a regular CLR property and not a dependency property.

ActualWidth is a calculated property. The calculations are a result of a layout pass, where the object is sized in layout according to the logic of its successive layout parents. For more info see Define layouts with XAML.

ActualWidth can have multiple or incremental reported changes to the value because of operations by the layout system. If you get the value while layout is still iterating, the layout system might still be calculating the required measure of space for child objects, constraints by the parent object, and so on. Because the value is based on an actual rendering pass, it may lag slightly behind the set value of properties like Width, which can be the basis of the input change.

BaseUriBaseUriBaseUriBaseUri

Gets a Uniform Resource Identifier (URI) that represents the base Uniform Resource Identifier (URI) for an XAML-constructed object at XAML load time. This property is useful for Uniform Resource Identifier (URI) resolution at run time.

public : Uri BaseUri { get; }

Uri BaseUri();

public Uri BaseUri { get; }

Public ReadOnly Property BaseUri As Uri

Value

UriUri

The base Uniform Resource Identifier (URI) for an object at XAML load time.

Examples

This example uses BaseUri in an event handler that resets an image source to a backup/default. BaseUri is used for the "path" part of a new Uniform Resource Identifier (URI) that is used for a BitmapImage constructor call, the rest of the Uniform Resource Identifier (URI) points to an image file that the app has in its resources. To see this code in context, see the CameraCaptureUI sample.

Remarks

The XAML parser can evaluate references to resources based on the context of the object in a page, and can thus evaluate what appear to be partial paths in a Uniform Resource Identifier (URI) property. For run-time code, the definition rules for the Uniform Resource Identifier (URI) types don't permit partial paths. At run time, you can use BaseUri from the scope of an object that was created by parsing a XAML page in order to get the "path" part of a Uniform Resource Identifier (URI), and then complete the Uniform Resource Identifier (URI) with a particular resource reference.

Windows 8 behavior

In Windows 8, the URI returned by BaseUri from style or template parts could return values that represented a project default rather than a value that was specific for the XAML file that created an object. The BaseUri behavior has been corrected starting with Windows 8.1. But if you relied on the previous behavior of BaseUri and changed your XAML compositions or resource lookups because of it, you might want to examine the areas of your code that make BaseUri calls. Verify that the combined Uniform Resource Identifier (URI) you use for finding resources or localization info work as expected when your app is recompiled for Windows 8.1. Apps that were compiled for Windows 8 but running on Windows 8.1 continue to use the Windows 8 behavior.

ClipPropertyClipPropertyClipPropertyClipProperty

CompositeModeCompositeModeCompositeModeCompositeMode

Gets or sets a property that declares alternate composition and blending modes for the element in its parent layout and window. This is relevant for elements that are involved in a mixed XAML / Microsoft DirectX UI.

Examples

This example sets the DataContext directly to an instance of a custom class.

// Create an instance of the MyColors class
// that implements INotifyPropertyChanged.
MyColors textcolor = new MyColors();
// Brush1 is set to be a SolidColorBrush with the value Red.
textcolor.Brush1 = new SolidColorBrush(Colors.Red);
// Set the DataContext of the TextBox MyTextBox.
MyTextBox.DataContext = textcolor;

' Create an instance of the MyColors class
' that implements INotifyPropertyChanged.
Dim textcolor As New MyColors()
' Brush1 is set to be a SolidColorBrush with the value Red.
textcolor.Brush1 = New SolidColorBrush(Colors.Red)
' Set the DataContext of the TextBox MyTextBox.
MyTextBox.DataContext = textcolor

Remarks

Data context is a concept where objects can inherit data binding information from successive parent objects in an object relationship hierarchy.

The most important aspect of data context is the data source that is used for data binding. A typical use of DataContext is to set it directly to a data source object. This data source might be an instance of a class such as a business object. Or you can create a data source as an observable collection, so that the data context enables detecting changes in the backing collection. If the data source is defined by a library that is also included in the project, setting a DataContext is often combined with instantiating the data source as a keyed resource in a ResourceDictionary, and then setting the DataContext in XAML with a {StaticResource} markup extension reference.

Another technique for setting DataContext is to add it to the root of the runtime object tree, as part of app initialization initialization logic, just after calling InitializeComponent. This technique is shown in Data binding overview.

In addition to specifying the source, a data context can also store additional characteristics of a binding declaration, such as a path into the data source.

Setting a DataContext is convenient for setting several bindings of different properties on the same object to a shared data context. However, it is valid for a DataContext to be undefined, and for all the necessary binding qualifications to exist in separate binding statements.

How you implement the object data source varies depending on your requirements and your programming language. For more info, see Data binding in depth.

A common scenario for C# and Microsoft Visual Basic data contexts is to use a CLR-defined business object that supports change notification. For a business object, the custom class used as data context typically implements INotifyPropertyChanged, so that updates to the data can update a one-way or two-way binding. If the data source is a collection of business objects, it can implement INotifyCollectionChanged plus list support (IList or List), or derive from ObservableCollection.

FlowDirectionFlowDirectionFlowDirectionFlowDirection

Gets or sets the direction in which text and other UI elements flow within any parent element that controls their layout. This property can be set to either LeftToRight or RightToLeft. Setting FlowDirection to RightToLeft on any element sets the alignment to the right, the reading order to right-to-left and the layout of the control to flow from right to left.

The direction that text and other UI elements flow within their parent element, as a value of the enumeration. The default value is LeftToRight.

Examples

This XAML example illustrates how a layout container such as Grid interprets a value of RightToLeft. If you look at the UI that this XAML produces, the "Chartreuse" rectangle appears in the top right, not the top left as it would when FlowDirection is the default LeftToRight.

Remarks

FlowDirection is intended for support of right-to-left layout for apps. Basically, setting FlowDirection to RightToLeft should produce an appropriate right-to-left behavior and rendering of any XAML control that it is applied to. Specific XAML controls may have further handling within their templates or logic that responds to FlowDirection of RightToLeft that isn't noted in this topic, and this might be noted in the reference topics for those XAML controls.

An object inherits the FlowDirection value from its parent in the object tree. Any element can override the value it gets from its parent. If not specified, the default FlowDirection is LeftToRight.

Within the element, the coordinate frame of reference is flipped horizontally such that "(0, 0)" will be the top right corner. This affects the values returned by hit test API such as FindElementsInHostCoordinates.

For layout containers, the coordinate frame of reference changes. "(0, 0)" in a Canvas is the top right corner. The "0" column in a Grid for purposes of Grid.Column is the rightmost column.

Within a control's template composition, the same layout changes apply. For example, if you set FlowDirection as RightToLeft for a RadioButton, the clickable button graphic will appear to the right of the text label content, because the Grid within the RadioButton template now treats "0" as the rightmost column, and the text label is right-aligned.

Image has a special behavior, see "FlowDirection for Image" section below.

Text in text containers such as TextBlock or TextBox does not flip horizontally if FlowDirection is RightToLeft, neither the whole string nor individual characters or glyphs are flipped. The order of Inline elements in an InlineCollection does not change either. This enables mixing content in an otherwise right-to-left app, such as including deliberate English language strings in an Arabic language UI. Any string that is intended to be a text source for a text container where the intended language is a right-to-left language should specify that string in the appropriate Unicode representation, which will be correctly presented in a text container. However, a value of FlowDirection as RightToLeft in a text container does change the default TextAlignment value such that the right edge of the text is right-aligned with the text container bounds.

FlowDirection has no visible effect on text in a Glyphs element but does change the element's hit testing and coordinate frame of reference.

FlowDirection for Image and MediaElement

If you set FlowDirection as RightToLeft for an Image, the visual content of an Image is flipped horizontally. However, an Image element does not inherit the FlowDirection value from any parent element. Typically you only want image-flipping behavior in images that are relevant to layout, but not necessarily to elements that have embedded text or other components that wouldn't make sense flipped for a right-to-left audience. To get image-flip behavior, you must set the FlowDirection element on the Image element specifically to RightToLeft, or set the FlowDirection property in code-behind. Consider identifying the Image element by x:Uid directive, and specifying FlowDirection values as a RESW resource, so that your localization experts can change this value later without changing the XAML or code.

MediaElement also does not inherit FlowDirection value from any parent element. If you do explicitly set FlowDirection as RightToLeft on MediaElement, then the media view area is flipped horizontally, similar to how an Image flips. Doing this deliberately should be even more rare than Image, because it's likely that any media source used in localized content already has any right-to-left issues corrected in the source media file.

Remarks

Height is one of three writable properties on FrameworkElement that specify height information. The other two are MinHeight and MaxHeight. If there is a conflict between these values, the order of application for actual height determination is that first MinHeight must be honored, then MaxHeight, and finally, if it is within bounds, Height.

Several of the FrameworkElement derived types are also derived from Shape. Not all of the Shape classes use Height or Width to specify their appearance, and instead use specific properties that might define a set of points. In this case a Height or Width is calculated, but is not typically set directly.

Custom classes might have similar considerations where the class might have properties that are more meaningful for specifying dimensions than are Height or Width. Height or Width are both still available as members and are settable.

The object where the Height or Width properties are set is almost always a child object in another parent's child collection, and setting Height or Width to a value is only a suggested value for the layout process. The layout system as well as the particular layout logic of the parent's class will use the value as a nonbinding input during the layout process, and might have to clip, resize the object, resize the container, or some combination of these behaviors that spans multiple participating objects in layout. Margin and padding also influences the available size. For more info, see Alignment, margin, and padding.

The return value of this property is always the same as any value that was set to it. In contrast, the value of the ActualHeight property may vary. The variance can occur either statically, because the layout rejected the suggested size, or momentarily. The layout system itself works asynchronously relative to the property system's set of Height, and the layout system might not have processed that sizing property change yet.

Also, do not set Height to a value that is significantly larger than the maximum size of any possible visual display.

"Auto" layout and Double.NaN

The default value of Height and Width is not 0, it is Double.NaN. Height and Width support the ability to be an unset "Auto" value. Because Height and Width are Double values, Double.NaN is used as a special value to represent this "Auto" behavior. The layout system interprets the "Auto" value to generally mean that the object should be sized to the available size in layout, instead of to a specific pixel value. If you want the "Auto" behavior for an object when it is used in layout, leave Height and Width unset at their Double.NaN default value. If you have previously set values and want to reenable the "Auto" behavior with run-time code, set to Double.NaN. In XAML such as templates, you can set attribute values using the string "Auto".

Note

Visual C++ component extensions (C++/CX) doesn't have a constant for NaN, it uses a value, which appears as "-1.#IND" followed by zeros.

Remarks

Alignment properties are intended to hint the desired layout to an adaptive layout container. They're typically set on FrameworkElement children and interpreted by another FrameworkElement container parent (typically a ContentControl derived class or a Panel derived class, or perhaps a presenter). Setting alignment properties on a child element is no guarantee that anything happens; the behavior depends on the layout composition and the parent elements involved.

When the Height and Width properties are explicitly set or calculated on an object, those measurements are more important to typical layout logic, and can cancel the effects of setting HorizontalAlignment to Stretch. Layout constraint properties (such as MaxWidth ) also affect the maximum or minimum layout size for a Stretch layout situation. Stretch is the default so that it's easier to use adaptive layout techniques in the cases where there is no explicit measurement. But if there are either Height and Width or clipping, the layout acts as if the value is Top for VerticalAlignment, typically Left for HorizontalAlignment (Right for right-to-left culture info or explicit FlowDirection values). For more info, see Alignment, margin, and padding.

Canvas does not use HorizontalAlignment when composing layout, because Canvas is based on absolute positioning. In general, the value of HorizontalAlignment is potentially treated differently by any object that is capable of having one or more FrameworkElement objects as child content. Each such parent object can have its own layout logic.

Each XAML UI element might apply this property differently based on the Style setters for the implicit style. The apparent "default value" for HorizontalAlignment in each UI element can be different. For example, a Button control starts with the value Left. If the UI element is a control, the HorizontalAlignment value might also affect the control's visual template.

LanguageLanguageLanguageLanguage

Gets or sets localization/globalization language information that applies to a FrameworkElement, and also to all child elements of the current FrameworkElement in the object representation and in UI.

public : Platform::String Language { get; set; }

winrt::hstring Language(); void Language(winrt::hstring language);

public string Language { get; set; }

Public ReadWrite Property Language As string

<frameworkElement Language="languageString" .../.

Value

stringstring

A string specifying language and culture that follows the Internet Engineering Task Force (IETF) BCP 47 standards. For example, U.S. English is "en-US".

Remarks

The Language property is intended for setting a per-element language setting on selected elements in a larger UI. The main reason for doing this is to influence text-related properties and settings, such as what the default or fallback FontFamily should be for text presentation.

If it's not specifically set as an attribute, the default value for Language is determined by other, larger factors that influence the globalization and localization settings for your app. This includes the user's system settings. For more info, see Globalizing your app.

Setting Language on UI elements is only a small part of what you might do to prepare an app for localization and globalization. For example, you typically need to name or load resources such as strings and images and include these resources in your app package. You also need to apply x:Uid directive values to any elements that should use resource qualifiers to obtain the language-specific resource. For more info, see Globalizing your app.

When you set Language in markup, you should consider using a RESW resources file to specify the BCP 47 string, rather than hard-coding a string in the markup. Specify an x:Uid directive value on that element where you want to specify Language so that the resource system can target the element. Then provide a string resource of the BCP 47 string that matches the resources folder name the resource comes from. You'll probably already have a RESW file in your project that is providing the conventional localized UI strings. For more info, see Quickstart: Translating UI resources.

FrameworkElement.Language and xml:lang

XAML is a language that is based on XML and follows basic XML rules. This includes supporting XML constructs such as the lang attribute from the XML language XML namespace. You can specify xml:lang on an object element for a FrameworkElement subclass, and it is treated the same as if it were a Language value, because it uses the same BCP 47 handling of the string attribute value. You can also specify xml:lang on an object element that is not a FrameworkElement subclass, although that typically won't result in any behavior change on that element.

Language deliberately uses a property inheritance structure so that a value for Language set on the root element will propagate that value to all child objects in the visual tree that are also a FrameworkElement. This parallels the xml:lang behavior in XML and the XML DOM. Also, you can use Language at run time to read an xml:lang value that was set in the markup, so long as the element you're reading from is a FrameworkElement subclass that has a Language property.

However, you can't specify both the Language and xml:lang attributes on the same object element, that will throw a XAML parse error.

Migration notes

This API takes a string. In the equivalent Microsoft Silverlight and Windows Presentation Foundation (WPF) API, the type of this property is a helper object that wraps the same string. You can import XAML from other projects without noticing this difference, because how XAML parses the string is identical.

Provides margin values for the object. The default value is a default Thickness with all properties (dimensions) equal to 0.

Examples

This example sets Margin in code as part of a larger scenario of creating a UI element at run time, and then setting various layout-related properties. This is often done prior to adding a new element to an existing XAML UI page's object tree. In this case several Margin properties are set using a new Thickness created with the uniform-value constructor.

Remarks

Margin behavior and layout

Margins are additive for peer objects in a layout; for example, two horizontally or vertically adjacent objects both with a margin of 30 set on the adjoining edge would have 60 pixels of space between them.

Objects that have margins set will not typically constrain the size of the specified Margin if the allotted rectangle space is not large enough for the margin plus the object's content area. The content area will be constrained instead when layout is calculated. The only case where margins would be constrained also is if the content is already constrained all the way to zero. However, this behavior is ultimately controlled by the specific type that is interpreting Margin, as well as the layout container of that object.

Negative values for margin dimensions are permitted, but should be used with caution (and be aware that negative margins can be interpreted differently by different class layout implementations). Negative margins typically clip the content of the object in that direction.

Non-integral values for margin values are technically permitted, but should typically be avoided.

Margin and Padding

A related concept is padding. For an object and its bounding box, the margin is extra space that is allocated to the outside of the bounding box when the UI element is contained and rendered. Padding is the area inside the bounding box, and affects the layout of any additional content or child objects inside the element. FrameworkElement does not define a padding property, However, several derived classes do define a Padding property. These include:

The maximum height of the object, in pixels. The default value is PositiveInfinity. This value can be any value equal to or greater than 0. PositiveInfinity is also valid.

Examples

This XAML example shows a technique of specifying a MaxHeight for a ViewBox. ViewBox is a decorator that can apply layout information to a single child and divide layout areas for the next parent element (in this case a StackPanel ).

Remarks

MaxHeight is one of three writable properties on FrameworkElement that specify height information. The other two are Height and Height. If there is a conflict between these values, the order of application for actual height determination is that first MinHeight must be honored, then MaxHeight, and finally, if it is within bounds, Height. All of these properties are recommendations to the layout behavior of the element's parent in the object tree. The height of the object after layout runs is available as the ActualHeight property value.

The final ActualHeight of an element might exceed MaxHeight. For example, if UseLayoutRounding is set to true and your app is running on a display with a Resolution Scale greater than 100%, then the ActualHeight may be rounded up to help ensure your UI doesn't look blurry when scaled.

The maximum width of the object, in pixels. The default is PositiveInfinity. This value can be any value equal to or greater than 0. PositiveInfinity is also valid.

Examples

This XAML example shows a technique of specifying a MaxWidth for a ViewBox. ViewBox is a decorator that can apply layout information to a single child and divide layout areas for the next parent element (in this case a StackPanel ).

Remarks

MaxWidth is one of three writable properties on FrameworkElement that specify width information. The other two are MinWidth and Width. If there is a conflict between these values, the order of application for actual width determination is that first MinWidth must be honored, then MaxWidth, and finally, if it is within bounds, Width. All of these properties are recommendations to the layout behavior of the element's parent in the object tree. The width of the object after layout runs is available as the ActualWidth property value.

The final ActualWidth of an element might exceed MaxWidth. For example, if UseLayoutRounding is set to true and your app is running on a display with a Resolution Scale greater than 100%, then the ActualWidth may be rounded up to help ensure your UI doesn't look blurry when scaled.

The minimum height of the object, in pixels. The default is 0. This value can be any value equal to or greater than 0. However, PositiveInfinity is not valid.

Remarks

MinHeight is one of three writable properties on FrameworkElement that specify height information. The other two are MaxHeight and MaxHeight. If there is a conflict between these values, the order of application for actual height determination is that first MinHeight must be honored, then MaxHeight, and finally, if it is within bounds, Height. All of these properties are recommendations to the layout behavior of the element's parent in the object tree. The height of the object after layout runs is available as the ActualHeight property value.

The minimum width of the object, in pixels. The default is 0. This value can be any value equal to or greater than 0. However, PositiveInfinity is not valid.

Remarks

MinWidth is one of three writable properties on FrameworkElement that specify width information. The other two are MaxWidth and Width. If there is a conflict between these values, the order of application for actual width determination is that first MinWidth must be honored, then MaxWidth, and finally, if it is within bounds, Width. All of these properties are recommendations to the layout behavior of the element's parent in the object tree. The width of the object after layout runs is available as the ActualWidth property value.

NameNameNameName

Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name.

public : Platform::String Name { get; set; }

winrt::hstring Name(); void Name(winrt::hstring name);

public string Name { get; set; }

Public ReadWrite Property Name As string

<frameworkElement Name="xamlNameString"/>

Value

stringstring

The name of the object, which must be a string that is valid in the XamlName grammar (see table in x:Name attribute reference). The default is an empty string.

Examples

This example gets a value for Name from an existing object, and uses that name to retarget an animation. You target an animation by setting the Storyboard.TargetName attached property.

private void Start_Animation(object sender, PointerRoutedEventArgs e)
{
// If the Storyboard is running and you try to change
// properties of its animation objects programmatically,
// an error will occur.
myStoryboard.Stop();
// Get a reference to the rectangle that was clicked.
Rectangle myRect = (Rectangle)sender;
// Change the TargetName of the animation to the name of the
// rectangle that was clicked.
myDoubleAnimation.SetValue(Storyboard.TargetNameProperty, myRect.Name);
// Begin the animation.
myStoryboard.Begin();
}

Private Sub Start_Animation(ByVal sender As Object, ByVal e As PointerRoutedEventArgs)
' If the Storyboard is running and you try to change
' properties of its animation objects programmatically,
' an error will occur.
myStoryboard.Stop()
' Get a reference to the rectangle that was clicked.
Dim myRect As Rectangle = CType(sender, Rectangle)
' Change the TargetName of the animation to the name of the
' rectangle that was clicked.
myDoubleAnimation.SetValue(Storyboard.TargetNameProperty, myRect.Name)
' Begin the animation.
myStoryboard.Begin()
End Sub

Remarks

The most common usage of this property is to specify the x:Name attribute for an object in XAML markup, or to read that value as it was set in markup. In most ways, the x:Name attribute and the Name property are equivalent. On any single element, the x:Name attribute and the Name property are mutually exclusive as XAML attributes; if you attempt to set both x:Name and Name on the same object element in markup, a parser error is thrown.

When you use the default Page build actions for XAML, any XAML element that has a x:Name attribute or Name generates field references that are eventually populated by InitializeComponent when the XAML is loaded. The field references enable a programming model whereby objects can be directly referenced by name in your page-specific code-behind, once the XAML object tree is loaded into a page or app.

Names must be unique in a XAML namescope. Generally, the XAML namescope is defined by the XAML page, but certain features such as templates or calls to API such as XamlReader.Load can define separate XAML namescopes. For more info, see XAML namescopes.

Name should never be localized. Name is used as a field name variable in code-behind. Such code is typically inaccessible to the localizer who might otherwise have access to XAML files that define the UI, although this depends on your deployment model and localization procedures. This is one reason why you should not display any strings that come from Name in your app UI.

Scenarios for Name

Setting x:Name or Name in the XAML that defines UI elements supports several major scenarios: + Animation targeting To apply an animation to an object property, you must target a specific instance. You do that by setting the Storyboard.TargetName attached property on any Timeline. The value that you set here is the string that you assigned as the x:Name or Name. For more info, see Storyboarded animations.

Parts of a control template In order to support the visual state model and control initialization, control authors should specify Name values for the key parts of a templated control. For more info see Quickstart: Control templates.

General run time interaction For example, code within an event handler might handle an event on an object that provides the change UI, but the change to properties occurs on another nearby UI element. The easiest way to write code for this situation is to use the field reference generated from a Name.

FindName

The utility method FindName, which is available from any FrameworkElement, can find objects by name in the object tree as long as they are in the current XAML namescope. FindName searches the XAML-created object tree in its entirety. Technically, what FindName is actually searching is the XAML namescope, which does not preserve the tree metaphor and is instead represented as a hash table of names. FindName cannot find names that are defined in applied templates. To find items in applied templates, use VisualTreeHelper.GetChild to get the applied template root object. Then you can call FindName on that root object, and you will be searching the XAML namescope of the template rather than the greater page.

Name and data binding

You cannot use the string value of Name as a direct source value for a data binding source. If you have to display the same string value as Name in UI with binding, you should replicate the same value to the Tag property, which can be used as a property binding source. Also don't use Name as a binding target.

Setting Name in code

You can set the value of Name for an object at run time, but there are some important considerations and limitations that you should be aware of.

Changing the value of Name in code at run time if the object had a previous Name value set in XAML is generally not recommended. This is because setting a name after the object tree is loaded will not create or change the identifying name of the equivalent field reference. If a field reference already exists because x:Name is provided in the initial markup, and you change the value of Name, the field and the name that you need to use to find the object through FindName are now different because the field remains as the markup-defined name.

Setting a Name value for an object that was created in code and therefore never had a XAML-defined Name value is appropriate for certain scenarios. One such scenario is if you want to be able to find either XAML-created or code-created objects in the tree by using FindName as the common utility function. In order to make that scenario work, the Windows Runtime continues to use and add to the XAML namescope hashtable representation at run time. If you are attempting to add new named objects to an existing largely XAML-created object tree, names must be unique, otherwise a duplicate name exception occurs. The duplicate name exception might not occur on the attempt to set Name. Until you attempt to add the duplicate-named object to the main object tree, the new object has its own self-contained XAML namescope. It is only at the moment that you connect the object to a larger object tree that the duplicate name condition can be detected. Or, the exception might occur on the operation that connected objects in the tree, for example on a call to the Add method of a collection that connects to the main object tree.

It can be difficult to know which Name values already exist in the XAML namescope that you will later add the new object to. There is no specific API that reports the full hashtable of existing names in a XAML namescope. If you set Name values in code extensively, you might need a technique for generating name strings that are unique to your run time usage, or you might need to wrap calls that add newly named objects in a try-catch block to catch the exceptions that could result from a duplicate name. Or you can add your own code to the InitializeComponent implementation that reads the XAML-generated name values.

Note that you can only set Name at run time for objects that are a FrameworkElement or an Inline. If an object does not have a Name property, and setting the name in XAML would have required using the x:Name attribute rather than Name, there is no run-time API available for setting such an object's run-time name.

Remarks

Parent can be null if an object was instantiated, but is not attached to an object that eventually connects to a page object root. In the default Windows Runtime classes, the parent of a FrameworkElement can also be expected to be a FrameworkElement subclass if it's not null. But custom classes might introduce a content model where this assumption is not true.

Note that the parent of an object can change if you adjust your app's object tree at run time. You typically should get the parent object value immediately before you need it for other operations, and should not rely on the value past this point.

Parent is read-only. You can change the parent of an object in most cases, but is done through manipulation of collections of the existing parent and a new parent. For example, you can add or remove from Children of a Panel.

Generally, you can conceive of the object tree of a UWP app using C++, C#, or Visual Basic as representing a nested series of objects and property values. If a given object has one or more contained children held in some type of Content or Children property, then Parent describes the inverse of that relationship. Most of the time, Parent is the same value as returned by VisualTreeHelper API. However, there may be cases where Parent reports a different parent than VisualTreeHelper does.

Remarks

Changing the RequestedTheme value is effectively changing the resource lookup behavior for the element's default template. If you change the value to Light then the template uses the values from the ResourceDictionary that is keyed as "Light" in the ThemeDictionaries collection. Setting the UI theme differently from the app's theme is often appropriate for floating controls such as menus and flyouts.

You can change the value of the RequestedTheme property for any given element at run-time. That's in contrast to the Application.RequestedTheme property, which throws an exception if you try to set it while the app's running.

The RequestedTheme value you set on a FrameworkElement will inherit to any elements that are nested within the element where RequestedTheme is set, but that inheritance can be overridden by explicitly setting RequestedTheme again. For example, in this XAML example, the parent StackPanel sets the theme to Light, and that value inherits to the first TextBlock child element, but not to the second TextBlock because it's setting the value to Dark instead.

Using XAML resource definitions and resource references is the typical way to use the Resources property. Most of the time XAML alone can handle common resource scenarios. But you also can use the property to access the collection API and thus retrieve resources with runtime code, if that's needed by your scenario. This example shows code access to the Resources property. In this example the Resources property references is inline and immediately followed by an indexer usage that retrieves a ResourceDictionary item with the string key RainbowBrush. Note the explicit cast; the return value for items from the ResourceDictionary is always a nontyped object.

A ResourceDictionary is a keyed collection, which is based on an IMap; template if you are programming with Visual C++ component extensions (C++/CX), or an IDictionary<TKey,TValue> template if you are programming with C# or Microsoft Visual Basic. The API you use in code to work with the dictionary and its items are reflective of the underlying template and thus of the language you're using for your app.

Application also has a Resources property, which can be used to store resources that should be accessible from more than one page in the app. Resources for custom controls can also be stored in a separate XAML file that is created by the default project template of a templated control.

The applied style for the object, if present; otherwise, null. The default for a default-constructed FrameworkElement is null.

Remarks

Setting the Style property directly is not the most common way to style a UI element's appearance. Instead, you influence a UI element's appearance through one of the these techniques:

You often set individual UI properties of a UI element as attributes in XAML. FrameworkElement.Style only applies to the current element, and any value from a Style**FrameworkElement.Style** is overwritten by a local property value, so setting the local value is more direct and more predictable. For more info on how a Style value and a local property value relate, see Dependency properties overview.

Control authors typically write a control that is templatable, but also comes with a default template. Your app can use the control and change its appearance by providing a new ControlTemplate, which is part of a Style defined in resources. This style is typically applied using the implicit style feature, not by setting Style. For more info, see Styling controls.

Control authors also expose properties that reference parts of a control that can have styles or values applied to just that part, so you don't have to totally retemplate the control. Here you're setting a more specific property, not FrameworkElement.Style.

The visual state model frequently resets the style of control at run time in response to changes in states that manifest themselves to the users visually. For example, control templates typically have a "Focused" state that adds a visual focus indicator to the control appearance so that a keyboard user can see which element in UI has the current keyboard focus. For more info on the visual state concept, see Quickstart: Control templates.

You can change the values of individual properties that have been set within a style. For example, you can set the Template property at run time even if this property has been set by a style. Or you can add setters to the collection in Setters. However, as soon as that style is placed in use by a loaded object, the Style should be considered sealed. You can detect this state by checking the value of IsSealed for the Style. A style is considered to be in use as soon as it is referenced by a loaded object that is connected to the object tree of a displayed page of UI. A Style and its Setters can also be considered sealed when the object using that style raises its Loaded event. Attempting to change an individual property of an in-use style (such as a property in the Setters collection) throws an exception.

Classes derived from Control have an additional entry point that is useful to control authors in regard to style and template application. FrameworkElement defines the virtual callback OnApplyTemplate that is invoked prior to Loaded. Classes derived from Control can override this callback to adjust the property values that were set by templates before the style is in use.

If queried at run time, the Style property does not return styles that come from an applied template, or active visual states. It only returns styles that were explicitly set by the Style property. In addition, it does not return implicit styles.

The intended arbitrary object value. This property has no default value.

Remarks

The scenario for the Tag property is to provide an general-purpose property on all FrameworkElement classes that supports data binding, animation and styles for itself but where the property's value does not have any implicit meaning to platform subsystems like layout, app model, text, input and so on. For example, you might put a value in the Tag property that has no meaning to the FrameworkElement where it is set, but which could be useful as an ElementName binding value to some other element that uses the FrameworkElement as a DataContext and processes the Tag value in its own way. Or you might use Tag as a way for an applied style to get a value from an arbitrary FrameworkElement parent into a specific applied template using {TemplateBinding} markup extension, without requiring XAML namespace mapping of a specific instance property in app XAML.

Remarks

Alignment properties are intended to hint the desired layout to an adaptive layout container. They're typically set on FrameworkElement children and interpreted by another FrameworkElement container parent (typically a ContentControl derived class or a Panel derived class, or perhaps a presenter). Setting alignment properties on a child element is no guarantee that anything happens; the behavior depends on the layout composition and the parent elements involved.

When the Height and Width properties are explicitly set or calculated on an object, those measurements are more important to typical layout logic, and can cancel the effects of setting VerticalAlignment to Stretch. Layout constraint properties (such as MaxHeight ) also affect the maximum or minimum layout size for a Stretch layout situation. Stretch is the default so that it's easier to use adaptive layout techniques in the cases where there is no explicit measurement. But if there are either Height and Width or clipping, the layout acts as if the value is Top for VerticalAlignment, typically Left for HorizontalAlignment (Right for right-to-left culture info or explicit FlowDirection values). For more info, see Alignment, margin, and padding.

Canvas does not use VerticalAlignment when composing layout, because Canvas is based on absolute positioning. In general, the value of VerticalAlignment is potentially treated differently by any object that is capable of having one or more FrameworkElement objects as child content. Each such parent object can have its own layout logic.

Each XAML UI element might apply this property differently based on the Style setters for the implicit style. The apparent "default value" for VerticalAlignment in each UI element can be different. For example, a Button control starts with the value Center. If the UI element is a control, the VerticalAlignment value might also affect the control's visual template.

Remarks

Width is one of three writable properties on FrameworkElement that specify width information. The other two are MinWidth and MaxWidth. If there is a conflict between these values, the order of application for actual width determination is that first MinWidth must be honored, then MaxWidth, and finally, if it is within bounds, Width.

Several of the FrameworkElement derived types are also derived from Shape. Not all of the Shape classes use Height or Width to specify their appearance, and instead use specific properties that might define a set of points. In this case a Height or Width is calculated, but is not typically set directly.

Custom classes might have similar considerations where the class might have properties that are more meaningful for specifying dimensions than are Height or Width. Height or Width are both still available as members and are settable.

The object where the Height or Width properties are set is almost always a child object in another parent's child collection, and setting Height or Width to a value is only a suggested value for the layout process. The layout system as well as the particular layout logic of the parent's class will use the value as a nonbinding input during the layout process, and might have to clip, resize the object, resize the container, or some combination of these behaviors that spans multiple participating objects in layout. Margin and padding also influences the available size. For more info, see Alignment, margin, and padding.

The return value of this property is always the same as any value that was set to it. In contrast, the value of the ActualWidth property may vary. The variance can occur either statically, because the layout rejected the suggested size, or momentarily. The layout system itself works asynchronously relative to the property system's set of Width, and the layout system might not have processed that sizing property change yet.

Also, do not set Width to a value that is significantly larger than the maximum size of any possible visual display.

"Auto" layout and Double.NaN

The default value of Height and Width is not 0, it is Double.NaN. Height and Width support the ability to be an unset "Auto" value. Because Height and Width are Double values, Double.NaN is used as a special value to represent this "Auto" behavior. The layout system interprets the "Auto" value to generally mean that the object should be sized to the available size in layout, instead of to a specific pixel value. If you want the "Auto" behavior for an object when it is used in layout, leave Height and Width unset at their Double.NaN default value. If you have previously set values and want to reenable the "Auto" behavior with run-time code, set to Double.NaN. In XAML such as templates, you can set attribute values using the string "Auto".

Note

Visual C++ component extensions (C++/CX) doesn't have a constant for NaN, it uses a value, which appears as "-1.#IND" followed by zeros.

Methods

Adds a routed event handler for a specified routed event, adding the handler to the handler collection on the current element. Specify handledEventsToo as true to have the provided handler be invoked even if the event is handled elsewhere.

Arrange(Rect)Arrange(Rect)Arrange(Rect)Arrange(Rect)

Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update.

Examples

This example implements ArrangeOverride to customize the "Arrange" pass logic for a custom panel implementation. Note in particular these aspects of the code:

Iterates over children.

For each child, calls Arrange, using a Rect where Height and Width are based on DesiredSize, and X and Y are based on logic that is specific to the panel.

Returns its size (in this case, this simple panel returns a fixed size rather than a size calculated on accumulating the arranged Rect value measurements).

// Second arrange all children and return final size of panel
protected override Size ArrangeOverride(Size finalSize)
{
// Get the collection of children
UIElementCollection mychildren = Children;
// Get total number of children
int count = mychildren.Count;
// Arrange children
// We're only allowing 9 children in this panel. More children will get a 0x0 layout slot.
int i;
for (i = 0; i < 9; i++)
{
// Get (left, top) origin point for the element in the 3x3 block
Point cellOrigin = GetOrigin(i, 3, new Size(100, 100));
// Arrange child
// Get desired height and width. This will not be larger than 100x100 as set in MeasureOverride.
double dw = mychildren[i].DesiredSize.Width;
double dh = mychildren[i].DesiredSize.Height;
mychildren[i].Arrange(new Rect(cellOrigin.X, cellOrigin.Y, dw, dh));
}
// Give the remaining children a 0x0 layout slot
for (i = 9; i < count; i++)
{
mychildren[i].Arrange(new Rect(0, 0, 0, 0));
}
// Return final size of the panel
return new Size(300, 300);
}

'Second arrange all children and return final size of panel
Protected Overrides Function ArrangeOverride(ByVal finalSize As Size) As Size
'Get the collection of children
Dim mychildren As UIElementCollection = Children
'Get total number of children
Dim count As Integer = mychildren.Count
'Arrange children
'only allowing 9 children in this panel. More children will get a 0x0 layout slot.
Dim i As Integer
For i = 0 To 8
'Get (left, top) origin point for the element in the 3x3 block
Dim cellOrigin As Point = GetOrigin(i, 3, New Size(100, 100))
'Arrange child
'Get desired height and width. This will not be larger than 100x100 as set in MeasureOverride.
Dim dw As Double = mychildren(i).DesiredSize.Width
Dim dh As Double = mychildren(i).DesiredSize.Height
mychildren(i).Arrange(New Rect(cellOrigin.X, cellOrigin.Y, dw, dh))
Next
For i = 9 To count - 1
'Give the remaining children a 0x0 layout slot
mychildren(i).Arrange(New Rect(0, 0, 0, 0))
Next
'Return final size of the panel
Return New Size(300, 300)
End Function
'Calculate point origin of the Block you are in
Protected Function GetOrigin(ByVal blockNum As Integer, ByVal blocksPerRow As Integer, ByVal itemSize As Size) As Point
'Get row number (zero-based)
Dim row As Integer = CInt(Math.Floor(blockNum / blocksPerRow))
'Get column number (zero-based)
Dim column As Integer = blockNum - blocksPerRow * row
'Calculate origin
Dim origin As New Point(itemSize.Width * column, itemSize.Height * row)
Return origin
End Function

Remarks

This method has a default implementation that performs built-in layout for most FrameworkElement derived classes. ArrangeOverride provides the behavior for Arrange, whenever Arrange is called either by internal layout logic or your own app's code, including any ArrangeOverride methods of your own for other classes. If you are producing a templated control, the ArrangeOverride logic defines your control's specific "Arrange" pass layout logic.

The general design of how elements go through a layout process when your app runs is divided into two steps: a "Measure" pass, and then an "Arrange" pass. Control authors (or panel authors) who want to customize the "Arrange" pass of layout processing should override ArrangeOverride. The implementation pattern should call Arrange on each visible child object, and pass the final desired size for each child object as the finalRect parameter. If Arrange isn't called, the child object is not rendered.

Several existing non-sealed classes provide override implementations of this method. Prominent ones include StackPanel and Grid. Typically, the behavior of ArrangeOverride produces a finalSize that does not violate any user-defined values that are placed on the layout container itself. For example, the finalSize is not typically larger than the container's Height and Width, accounting for Margin or Padding values that affect the content area. Controls that specifically have a scenario for exceeding the container size could return a larger value, but anyone using that control must account for the clipping and positioning issues that result from it. The value that an ArrangeOverride implementation passes to Arrange for each child object is generally the value that is set in DesiredSize by the previous Measure call.

Remarks

This API is part of the implementation detail of x:Load, and should not be used directly. Instead use the generated UnloadObject API in a page or user control. This will also release any references due to x:Name or x:Bind.

The requested object. This can be null if no matching object was found in the current XAML namescope.

Remarks

Important

In order to use the FindName method effectively, you should understand the concept of a XAML namescope, and how a XAML namescope is created at XAML load time and then referenced and possibly modified at run time. For more info see XAML namescopes.

The most common usage of FindName in your Windows Runtime code will be from within the generated InitializeComponent call for a XAML page. In this situation, FindName is invoked only after the XAML page is loaded. InitializeComponent provides the infrastructure such that any object that was instantiated by XAML loading can conveniently be accessed by your code-behind code. You can then reference the objects as a variable that shares the same name as the markup-declared x:Name attribute.

A run-time API such as FindName is working against a run-time object tree of the app as it exists in memory. When part of this object tree is created from templates or run-time loaded XAML, a XAML namescope is typically not contiguous within that object tree. The result is that there might be a named object in the object tree that a given FindName scope cannot find. The discontinuities between XAML namescopes that you might encounter in typical application scenarios are when objects are created by applying a template, or when objects are created by a call to XamlReader.Load and subsequently added to the object tree.

If you return an unexpected null result for FindName, try these techniques:

For named objects that come from a template, if you are defining or deriving from a control, you can call GetTemplateChild from the scope of the object where the template is applied. You must be in a derived-class definition scope in order to use GetTemplateChild, because it is a protected method of Control.

If you are not in a derived-class definition scope, you may be able to enter the visual tree of a template, by using VisualTreeHelper at a point in object lifetime after the template is applied (handle the Loaded event). VisualTreeHelper uses a parent-child metaphor for walking the tree, rather than using the XAML namescope concept. Walking the tree generally requires a specific knowledge of the control's composition as it comes from a given template. You can use VisualTreeHelper.GetChild on the control to get the control's applied template root, and call FindName specifically on the template root to access elements that are named within the template XAML.

For the XamlReader.Load case, you should preserve a reference to the return value of the XamlReader.Load call, which is an object that will become the owner or basis of the created XAML namescope that is relevant. Then call FindName from that scope instead.

The object returned by FindName is not necessarily a FrameworkElement. For example, you might apply a name to an animation storyboard, and the various animation storyboard types do not derive from FrameworkElement.

The Name property for an object (or the similar x:Name attribute) is assigned by specifying an attribute on an object element in XAML markup. You can set a Name value after the initial source XAML is loaded, but this technique has some limitations (see Remarks in Name ).

Name values that are added or changed at run time in the object tree will update into the acting XAML namescope at that level in the object tree. In other words, if you create a new FrameworkElement, give it a Name, then add it to the object tree, calling FindName from within that XAML namescope can find and return the code-created object.

true to use a VisualTransition to transition between states. false to skip using transitions and go directly to the requested state. The default is false.

Returns

boolbool

true if the control successfully transitions to the new state, or was already using that state; otherwise, false.

Remarks

The default implementation of FrameworkElement.GoToElementStateCore provides the normal state change behavior that's accessed by calling VisualStateManager.GoToState, and also the default control template / visual state loading behavior for any XAML control. You should only override FrameworkElement.GoToElementStateCore if you are prepared to take full responsibility for constructing the visual tree for a control in your code at run time. This includes presentation of any content that comes from content properties, child element collections, and so on.

InvalidateMeasureInvalidateMeasureInvalidateMeasureInvalidateMeasure

Measure(Size)Measure(Size)Measure(Size)Measure(Size)

Updates the DesiredSize of a UIElement. Typically, objects that implement custom layout for their layout children call this method from their own MeasureOverride implementations to form a recursive layout update.

The size that this object determines it needs during layout, based on its calculations of the allocated sizes for child objects or based on other considerations such as a fixed container size.

Examples

This example implements MeasureOverride to customize the "Measure" pass logic for a custom panel implementation. Note in particular these aspects of the code:

Iterates over children.

For each child, calls Measure, using a Size that makes sense based on how the panel logic treats the number of children and its own known size limit.

Returns its size (in this case, this simple panel returns a fixed size rather than a size calculated on accumulating the measurements).

// First measure all children and return available size of panel
protected override Size MeasureOverride(Size availableSize)
{
// Measure first 9 children giving them space up to 100x100, remaining children get 0x0
int i = 0;
foreach (FrameworkElement child in Children)
{
if (i < 9)
{
child.Measure(new Size(100, 100));
}
else
{
child.Measure(new Size(0, 0));
}
i++;
}
// return the size available to the whole panel, which is 300x300
return new Size(300, 300);
}

'First measure all children and return available size of panel
Protected Overrides Function MeasureOverride(ByVal availableSize As Size) As Size
'Measure first 9 children giving them space up to 100x100, remaining children get 0x0
Dim i As Integer = 0
For Each child As FrameworkElement In Children
If i < 9 Then
child.Measure(New Size(100, 100))
Else
child.Measure(New Size(0, 0))
End If
i += 1
Next
'return the size available to the whole panel, which is 300x300
Return New Size(300, 300)
End Function

Remarks

This method has a default implementation that performs built-in layout for most FrameworkElement derived classes. MeasureOverride provides the behavior for Measure, whenever Measure is called either by internal layout logic or your own app's code, including any MeasureOverride methods of your own for other classes. If you are producing a templated control, the MeasureOverride logic defines your control's specific "Measure" pass layout logic.

The general design of how elements go through a layout process when your app runs is divided into two steps: a "Measure" pass, and then an "Arrange" pass. Control authors (or panel authors) who want to customize the "Measure" pass of layout processing should override MeasureOverride. Your implementation should do the following:

Iterate your class's particular collection of child objects that are part of layout, and call Measure on each child object.

Immediately get DesiredSize on each child (this is set as a property after Measure is called).

Compute the net desired size of the parent, based on the running measurement of the size that is needed for child objects.
The return value of MeasureOverride should be the object's own desired size, which then becomes the Measure input for the parent of the current object. This same process continues through the layout system until the root of the page/object tree is reached. During this process, child objects might return a larger DesiredSize size than the initial availableSize to indicate that the child object wants more space. This might be handled in your own implementation by introducing a scrollable region, resizing the parent control, establishing some manner of stacked order, or any number of solutions for measuring or arranging content that can vary depending on your layout container's intended functionality.

OnApplyTemplate()OnApplyTemplate()OnApplyTemplate()OnApplyTemplate()

Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class.

protected : virtual void OnApplyTemplate()

void OnApplyTemplate() const;

protected virtual void OnApplyTemplate()

Protected Overridable Function OnApplyTemplate() As void

Examples

This example shows an OnApplyTemplate override defined by a custom control. The override is designed to account for callers potentially defining and applying their own control template through the template and style system. As part of its definition, the control attributes the named elements within a template that are required, such as "UpButton". Then OnApplyTemplate retrieves the object references based on this naming contract when the template is loaded, calling GetTemplateChild. (The values being set, for example "UpButtonElement", refer to private fields defined at class-level so that other members of the class can reference that part as an object at run time.) Also, this example calls the private method UpdateStates (definition not shown). This is another common scenario for OnApplyTemplate: making sure that the visual state is set for the control's starting state, in this case by calling a private method that accounts for all of the control's defined states and calls GoToState to set the appropriate state.

Notes to implementers

There is a base implementation of this method implemented as a Windows Runtime internal behavior, which provides some basic layout logic. You should always call the base implementation from your implementation. Failing to reference the base implementation might result in undesirable layout behavior.

Derived classes can use this method as a notification or entry point for the following scenarios:

Build the remainder of a visual tree using custom code.

Run code that can only work once the XAML-defined visual tree from templates has been applied. For example, code that obtains references to named elements that came from a template, by calling GetTemplateChild, so that members of these parts can be referenced by other post-template runtime code.

Introduce services that only make sense to exist after the visual tree from templates is complete.

Attach class-defined event handlers to parts of the template, or the control parent of a composite control. For example, you might want class logic to handle routed KeyDown events from a TextBox template part of a composite control. You would do this so that UI states are updated based on the low-level input event of the part, and other events that are specific to your control and raised by the control parent are raised instead.

Set states and properties of elements within the template that are dependent on other factors. For example, property values might only be discoverable by knowing the parent element, or when a specific derived class uses a common template. However, note that a well-designed control should handle its visual states with VisualStateManager. For more info on this concept, see Quickstart: Control templates.
OnApplyTemplate is often a more appropriate point to deal with adjustments to the template-created visual tree than is the Loaded event. The Loaded event might occur before the template is applied, and the visual tree might be incomplete as of Loaded.

You can bind to custom dependency properties or custom attached properties, the identifier you pass as the dp parameter doesn't have to be a Windows Runtime defined property.

Whether a binding created from code will be able to use an acting data context depends on object lifetime considerations. For example, a DataContext value that is set from XAML won't be available until the XAML is parsed. In that case you may want to use a Loaded handler to add bindings from code.

Binding to attached properties

You can put data bindings on any attached properties that a target object supports. Technically an DependencyObject supports all the possible attached properties, but you'd usually only set a binding on an attached property that's relevant to that object or your scenario. For example you would set a binding on Grid.Row only if you anticipate that the target element has a Grid parent that will use that info. Specify the dp parameter as the dependency property identifier that exists on the attached property's owner class (for the Grid.Row example, that identifier is Grid.RowProperty ). You won't find that identifier on the target because it's an attached property. For more info on attached properties, see Attached properties overview.

Public Event TypedEventHandler DataContextChanged( Of ( Of FrameworkElement ), ( Of DataContextChangedEventArgs ))

<frameworkElement DataContextChanged="eventhandler"/>

Remarks

The FrameworkElement.DataContext property has a built-in behavior whereby its value inherits to all FrameworkElement child elements of a FrameworkElement where a DataContext value is set. This behavior enables a set of related elements to use the same context to bind to different source properties, which is particularly useful for item templates, data templates, and other data binding scenarios. Because DataContext inherits, there's potential for each FrameworkElement that uses the inherited value to fire another DataContextChanged event that's sourced from the inheriting element, not the parent element, once the element detects that its inherited DataContext value has changed. If you don't want this behavior, you should handle the DataContextChanged event on the parent source, where the event will fire first. As part of your handler logic, set the value of the Handled property in the DataContextChangedEventArgs event data to true. That action will prevent the event from routing to child elements.

Note

DataContextChanged has routing behavior but isn't a true routed event (it does not have a RoutedEvent identifier). Also, it routes from parent to child whereas the true routed events route from child to parent. If you're familiar with Windows Presentation Foundation (WPF), DataContextChanged might be considered a tunneling routed event by the Windows Presentation Foundation (WPF) event routing definitions.

DataContextChanged is useful for scenarios where control logic or other code-based logic wants notification that the data context for bindings has changed, which often means that data bound values will change. This can be useful as a trigger to run code that makes context-driven changes, and then the new context can be used by existing bindings to recalculate values. It's also useful for cases where you don't want a pre-existing declared binding in data templates, but need a notification for changes. In this scenario you can handle DataContextChanged to detect changes to the data context and make direct changes to other properties in your code in response, just like a XAML-declared binding does dynamically through the data binding engine. For example, you might have a custom control that's mainly for use inside data templates, and you want the control to be able to perform binding operations without any explicit Binding declarations either in the app UI XAML or in the data template.

Remarks

LayoutUpdated is the last object lifetime event to occur in the XAML load sequence before a control is ready for interaction. However, LayoutUpdated can also occur at run time during the object lifetime, for a variety of reasons: a property change, a window resizing, or a runtime layout request (UpdateLayout or a changed control template). The LayoutUpdated event is fired after all SizeChanged events in a layout sequence occur.

LayoutUpdated can occur when the object where the handler is attached does not necessarily change anything in the visual tree under it. For instance, imagine a layout container where there are two child elements sharing space. If the first object changes a property that forces a new layout, both objects fire LayoutUpdated because the second object might be repositioned even if its own subsidiary layout does not change.

When you handle LayoutUpdated, do not rely on the sender value. For LayoutUpdated, sender is always null, regardless of where the handler is attached. This is to prevent handlers from assigning any meaning to sender, such as implying that it was that specific element that fired the event out of the visual tree. LayoutUpdated implies that something in the overall visual tree has changed, and each specific object anywhere in the tree has the option of handling this occurrence. If you're familiar with lower-level render API design, you can equate LayoutUpdated being fired as similar to a "redraw needed" flag being set as part of an object-driven, retained-mode rendering logic.

Because LayoutUpdated fires in many circumstances and isn't always specific to an object that actually changes, consider whether handling the SizeChanged event instead is more appropriate for your scenario.

Windows 8 behavior

Windows 8 had an issue with keeping track of multiple listeners for this event. If you had multiple listeners/handlers for the event, attempting to remove one of them would result in removing all of them. The issue is corrected starting with Windows 8.1; removing event handlers using the -= syntax correctly removes only one listener at a time. Most code won't need changes or behavior checks because dealing with multiple listeners per event is an uncommon scenario.

Apps that were compiled for Windows 8 but running on Windows 8.1 continue to use the Windows 8 behavior.

Examples

Handlers for Loaded and Unloaded are automatically attached to any page that uses the NavigationHelper class from the project templates for support. The event wiring is done in the constructor. The handler is written using a lambda, and attaches other event handlers so that page navigation can use mouse or keyboard events.

The Loaded event is a good time to start decorative animations that aren't tied to theme animations or other triggers. This example shows triggering a PointAnimation in XAML, by wiring a Loaded handler to a method that calls Begin on an animation Storyboard.

Remarks

Although this event uses the RoutedEventHandler delegate and RoutedEventArgs as event data, the event is not a routed event. It can be handled only on the element that originates the event (in other words, the sender). OriginalSource in event data for this event is always null.

Loaded and object lifetime

In the Windows Runtime implementation, the Loaded event is guaranteed to occur after a control template is applied, and you can obtain references to objects that are created by applying the XAML template.

The Loaded event can be used as a point to hook up event handlers on elements that come from a template, or to invoke logic that relies on the existence of child elements that are the result of an applied template. Loaded is the preferred object lifetime event for manipulating element tree structures with your app code prior to the display of XAML controls for your UI. It is also appropriate to call the VisualStateManager.GoToState method from a Loaded handler in order to set an initial view state that is defined in the template, if there's no other event that also occurs on initial layout (SizeChanged does occur on initial layout).

The timing of Loaded in the Windows Runtime implementation is similar to its timing in the Windows Presentation Foundation (WPF) implementation. In contrast, the Microsoft Silverlight implementation has a timing issue where you cannot rely on the template being loaded when Loaded occurred. If you are migrating XAML or code-behind from these XAML frameworks, you may want to adjust what you do in a Loaded handler to be appropriate for the template-load timing of the Windows Runtime implementation.

To access the items that come from an applied template, you can use the VisualTreeHelper static methods and navigate child elements by index. Or you can call the FindName method on the root element of the templated content to find a specific part of the template with a given x:Name attribute value. Note that you must call FindName on the template root rather than the control itself, because there is a XAML namescope created any time that objects are created by a template that is specific to that template (for more info, see XAML namescopes). To get to the template root, use VisualTreeHelper.GetChild(target,0) where target is the object where the template is applied. Once you've got that root you can get to the named parts thereafter.

If you are deriving from an existing control, instead of handling Loaded on a per instance basis, you can override OnApplyTemplate to make the behavior part of the default class behavior. OnApplyTemplate is specifically intended as the callback for this situation, where you have a tree of objects from the applied template and now you want to examine or adjust the visuals. This is a key part of defining behavior for a custom control, including actions such as declaring the starting visual states and wiring class handlers that can't be defined using the On* override pattern. One difference is that from the OnApplyTemplate scope you should use GetTemplateChild to find named parts rather than FindName.

LayoutUpdated is a related event. The LayoutUpdated event is the last "object lifetime" event in the sequence of enabling a control, and occurs after Loaded. However, LayoutUpdated is fired for objects that are involved in a layout change, not just successive parents in the tree. Several objects in a UI might all fire LayoutUpdated at the same time. Layout changes happen for a variety of reasons, such as the user changing the view state or screen resolution, or programmatic resize of other elements in the same UI or layout container. For this reason, Loaded is usually a better choice for running code that works with an initial layout or an applied template.

For app code that uses navigation between pages, do not use Page.OnNavigatedTo for element manipulation or state change of controls on the destination page. The OnNavigatedTo virtual method is invoked before the template is loaded, thus elements from templates aren't available yet. Instead, attach a Loaded event handler at the root of the newly loaded page's content, and perform any element manipulations, state changes, event wiring and so on in the Loaded event handler.

PointerPressedPointerPressedPointerPressedPointerPressed

PointerReleasedPointerReleasedPointerReleasedPointerReleased

Occurs when the pointer device that previously initiated a Press action is released, while within this element. Note that the end of a Press action is not guaranteed to fire a PointerReleased event; other events may fire instead. For more info, see Remarks.

SizeChanged occurs during initial layout of elements on a page, when the app first is activated, because the ActualHeight and ActualWidth values for UI elements are undefined before layout happens. They only get values during the initial layout pass and thus the SizeChanged event occurs. Thereafter, during an app's lifetime, the SizeChanged event can fire from an element again if the ActualHeight and ActualWidth values change for other reasons. These include:

Databinding values refreshed or new styles applied that affect any of the layout-related properties of FrameworkElement.

Code that adjusts the dimensions of a container like a Panel or ListBox that is the parent of an element. This often triggers a layout pass. Due to the new layout conditions, a contained child element might now have more or less space available, and that could result in a new ActualHeight and ActualWidth for an element within.

Other changes that happen at run-time that change layout space even if they're not directly changing FrameworkElement layout properties. For example, a list that's based on databinding to items might refresh or update, and that could cause size changes in items, items controls, list views, and so on. Or a list view that supports incremental loading might fetch more items and expand the list view.

The user changes the app Window size (Window.SizeChanged occurs), which in turn affects the size of the top-level Page and perhaps the adaptive layout-derived sizes of elements within that page that use "Auto" layout or Stretch alignment and didn't specify dimensions.

It is not strictly necessary to avoid calling other API that influence layout of the current object from within a SizeChanged handler. For example: setting Height or Width; calling InvalidateMeasure or UpdateLayout; calling ApplyTemplate; any operation that might resize child elements and thus invalidate the parent layout. The layout engine has internal logic that stabilizes the values before an object fires the event again, so the logic is usually robust enough to avoid looping conditions. However, it is still possible to inadvertently define sizing or rendering loops that can hang your app, which generally throws exceptions like LayoutCycleException rather than actually hanging. This happens if your handler logic combined with surrounding layout is not capable of reaching an end result for the size of the relevant object.

If the position of the object within a parent container changes, but not the size, SizeChanged won't occur.

LayoutUpdated is a similar event, but LayoutUpdated is also fired for position changes. Also, LayoutUpdated occurrence is not scoped to a specific object's layout properties, it's reporting on the entire visual tree that an object is contained in. LayoutUpdated informs you that something within the overall visual tree that contains the object has changed, but the layout specifics (size, position) of the object where the handler is attached might not have changed.

Although this event uses a RoutedEventHandler -related delegate and a RoutedEventArgs -derived class as event data, the event is not truly a routed event. It doesn't bubble through an object tree. It can be handled only on the element that originates the event (in other words, the sender). OriginalSource in event data for this event is always null, so don't try to use the OriginalSource.

Remarks

Although this event uses the RoutedEventHandler delegate and RoutedEventArgs as event data, the event is not truly a routed event. It can only be handled on the element that originates the event (in other words, the sender). OriginalSource in event data for this event is always null.