FrameworkElement FrameworkElement FrameworkElement Class

Definition

Provides a base element class for Windows Runtime UI objects. FrameworkElement defines common API that support UI interaction and the automatic layout system. FrameworkElement also defines API related to data binding, defining and examining the object tree, and tracking object lifetime.

public : class FrameworkElement : UIElement, IFrameworkElement, IFrameworkElement2, IFrameworkElement3, IFrameworkElement4, IFrameworkElementOverrides, IFrameworkElementOverrides2
public class FrameworkElement : UIElement, IFrameworkElement, IFrameworkElement2, IFrameworkElement3, IFrameworkElement4, IFrameworkElementOverrides, IFrameworkElementOverrides2
Public Class FrameworkElement Inherits UIElement Implements IFrameworkElement, IFrameworkElement2, IFrameworkElement3, IFrameworkElement4, IFrameworkElementOverrides, IFrameworkElementOverrides2
Inheritance
FrameworkElementFrameworkElementFrameworkElement
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

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.

Prominent API of FrameworkElement that support layout: Height, Width, ActualHeight, ActualWidth, Margin, MeasureOverride, ArrangeOverride, HorizontalAlignment, VerticalAlignment, LayoutUpdated.

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.

Prominent API of FrameworkElement that support object lifetime events: Loaded, SizeChanged, Unloaded, OnApplyTemplate.

Data binding

The ability to set a value for a potentially inherited data context for a data binding is implemented by FrameworkElement. FrameworkElement also has API for establishing data binding in code rather than in XAML. For more info, see Data binding in depth.

Prominent API of FrameworkElement that support data binding: DataContext, DataContextChanged, SetBinding, GetBindingExpression.

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.

Prominent API of FrameworkElement that support XAML and programming model: Name, FindName, Parent, BaseUri, OnApplyTemplate.

Globalization

The FrameworkElement class defines the Language property and the FlowDirection property. For more info, see Globalizing your app.

Style and theme support

The FrameworkElement class defines the Style property and the RequestedTheme property. Also, the Resources property is used to define the page-level XAML resource dictionaries that typically define styles and templates, as well as other shared resources. For more info, see Styling controls and ResourceDictionary and XAML resource references.

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:

Constructors

FrameworkElement() FrameworkElement() FrameworkElement()

Provides base class initialization behavior for FrameworkElement -derived classes.

protected : FrameworkElement()
protected FrameworkElement()
Protected Sub New()

Properties

AccessKey AccessKey AccessKey

Inherited from UIElement

AccessKeyProperty AccessKeyProperty AccessKeyProperty

Inherited from UIElement

AccessKeyScopeOwner AccessKeyScopeOwner AccessKeyScopeOwner

Inherited from UIElement

AccessKeyScopeOwnerProperty AccessKeyScopeOwnerProperty AccessKeyScopeOwnerProperty

Inherited from UIElement

ActualHeight ActualHeight ActualHeight

Gets the rendered height of a FrameworkElement. See Remarks.

public : double ActualHeight { get; }
public double ActualHeight { get; }
Public ReadOnly Property ActualHeight As double
Value
double double double

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.

For purposes of ElementName binding, ActualHeight does not post updates when it changes (due to its asynchronous and run-time calculated nature). Do not attempt to use ActualHeight as a binding source for an ElementName binding. If you have a scenario that requires updates based on ActualHeight, use a SizeChanged handler.

See Also

ActualHeightProperty ActualHeightProperty ActualHeightProperty

Identifies the ActualHeight dependency property. See Remarks.

public : static DependencyProperty ActualHeightProperty { get; }
public static DependencyProperty ActualHeightProperty { get; }
Public Static ReadOnly Property ActualHeightProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the ActualHeight dependency property.

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.

ActualTheme ActualTheme ActualTheme

Gets the UI theme that is currently used by the element, which might be different than the RequestedTheme.

public : ElementTheme ActualTheme { get; }
public ElementTheme ActualTheme { get; }
Public ReadOnly Property ActualTheme As ElementTheme
Value
ElementTheme ElementTheme ElementTheme

A value of the enumeration, for example Light.

Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

ActualThemeProperty ActualThemeProperty ActualThemeProperty

Identifies the ActualTheme dependency property.

public : static DependencyProperty ActualThemeProperty { get; }
public static DependencyProperty ActualThemeProperty { get; }
Public Static ReadOnly Property ActualThemeProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the ActualTheme dependency property.

Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

ActualWidth ActualWidth ActualWidth

Gets the rendered width of a FrameworkElement. See Remarks.

public : double ActualWidth { get; }
public double ActualWidth { get; }
Public ReadOnly Property ActualWidth As double
Value
double double double

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.

For purposes of ElementName binding, ActualWidth does not post updates when it changes (due to its asynchronous and run-time calculated nature). Do not attempt to use ActualWidth as a binding source for an ElementName binding. If you have a scenario that requires updates based on ActualWidth, use a SizeChanged handler.

See Also

ActualWidthProperty ActualWidthProperty ActualWidthProperty

Identifies the ActualWidth dependency property. See Remarks.

public : static DependencyProperty ActualWidthProperty { get; }
public static DependencyProperty ActualWidthProperty { get; }
Public Static ReadOnly Property ActualWidthProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the ActualWidth dependency property.

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.

AllowDrop AllowDrop AllowDrop

Inherited from UIElement

AllowDropProperty AllowDropProperty AllowDropProperty

Inherited from UIElement

AllowFocusOnInteraction AllowFocusOnInteraction AllowFocusOnInteraction

Gets or sets a value that indicates whether the element automatically gets focus when the user interacts with it.

public : Platform::Boolean AllowFocusOnInteraction { get; set; }
public bool AllowFocusOnInteraction { get; set; }
Public ReadWrite Property AllowFocusOnInteraction As bool
<frameworkElementAllowFocusOnInteraction="bool"/>
Value
Platform::Boolean bool bool

true if the element gets focus when a user interacts with it; otherwise, false.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

AllowFocusOnInteractionProperty AllowFocusOnInteractionProperty AllowFocusOnInteractionProperty

Identifies for the AllowFocusOnInteraction dependency property.

public : static DependencyProperty AllowFocusOnInteractionProperty { get; }
public static DependencyProperty AllowFocusOnInteractionProperty { get; }
Public Static ReadOnly Property AllowFocusOnInteractionProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the AllowFocusOnInteraction dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

AllowFocusWhenDisabled AllowFocusWhenDisabled AllowFocusWhenDisabled

Gets or sets whether a disabled control can receive focus.

public : Platform::Boolean AllowFocusWhenDisabled { get; set; }
public bool AllowFocusWhenDisabled { get; set; }
Public ReadWrite Property AllowFocusWhenDisabled As bool
Value
Platform::Boolean bool bool

true if a disabled control can receive focus; otherwise, false.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

AllowFocusWhenDisabledProperty AllowFocusWhenDisabledProperty AllowFocusWhenDisabledProperty

Identifies the AllowFocusWhenDisabled dependency property.

public : static DependencyProperty AllowFocusWhenDisabledProperty { get; }
public static DependencyProperty AllowFocusWhenDisabledProperty { get; }
Public Static ReadOnly Property AllowFocusWhenDisabledProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the AllowFocusWhenDisabled dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

BaseUri BaseUri BaseUri

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; }
public Uri BaseUri { get; }
Public ReadOnly Property BaseUri As Uri
Value
Uri Uri Uri

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.

void SDKSample::Page::Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    rootPage->NotifyUser("The photo will be shown here.", NotifyType::StatusMessage); 
    ResetButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed; 
    CapturedPhoto->Source = ref new BitmapImage(ref new Windows::Foundation::Uri(BaseUri->AbsoluteUri, "Assets/placeholder-sdk.png")); 
     // Remove file from Application Data 
    appSettings->Remove("capturedPhoto"); 
}
private void Reset_Click(object sender, RoutedEventArgs e)
{
    ResetButton.Visibility = Visibility.Collapsed;
    CapturedPhoto.Source = new BitmapImage(new Uri(this.BaseUri, "Assets/placeholder-sdk.png"));

    // Clear file path in Application Data 
    appSettings.Remove(photoKey);
}
Private Sub Reset_Click(sender As Object, e As RoutedEventArgs)
    ResetButton.Visibility = Visibility.Collapsed
    CapturedPhoto.Source = New BitmapImage(New Uri(Me.BaseUri, "Assets/placeholder-sdk.png"))
    ' Clear file path in Application Data 
    appSettings.Remove(photoKey)
End Sub

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.

CacheMode CacheMode CacheMode

Inherited from UIElement

CacheModeProperty CacheModeProperty CacheModeProperty

Inherited from UIElement

CanDrag CanDrag CanDrag

Inherited from UIElement

CanDragProperty CanDragProperty CanDragProperty

Inherited from UIElement

CharacterReceivedEvent CharacterReceivedEvent CharacterReceivedEvent

Inherited from UIElement

Clip Clip Clip

Inherited from UIElement

ClipProperty ClipProperty ClipProperty

Inherited from UIElement

CompositeMode CompositeMode CompositeMode

Inherited from UIElement

CompositeModeProperty CompositeModeProperty CompositeModeProperty

Inherited from UIElement

ContextFlyout ContextFlyout ContextFlyout

Inherited from UIElement

ContextFlyoutProperty ContextFlyoutProperty ContextFlyoutProperty

Inherited from UIElement

DataContext DataContext DataContext

Gets or sets the data context for a FrameworkElement when it participates in data binding.

public : Platform::Object DataContext { get; set; }
public object DataContext { get; set; }
Public ReadWrite Property DataContext As object
<frameworkElement DataContext="binding"/>
- or -
<frameworkElement DataContext="{StaticResource keyedObject}"/>
 
Value
Platform::Object object object

The object to use as data context.

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.

See Also

DataContextProperty DataContextProperty DataContextProperty

Identifies the DataContext dependency property.

public : static DependencyProperty DataContextProperty { get; }
public static DependencyProperty DataContextProperty { get; }
Public Static ReadOnly Property DataContextProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The DataContext dependency property identifier.

DesiredSize DesiredSize DesiredSize

Inherited from UIElement

Dispatcher Dispatcher Dispatcher

Inherited from DependencyObject

DoubleTappedEvent DoubleTappedEvent DoubleTappedEvent

Inherited from UIElement

DragEnterEvent DragEnterEvent DragEnterEvent

Inherited from UIElement

DragLeaveEvent DragLeaveEvent DragLeaveEvent

Inherited from UIElement

DragOverEvent DragOverEvent DragOverEvent

Inherited from UIElement

DropEvent DropEvent DropEvent

Inherited from UIElement

ExitDisplayModeOnAccessKeyInvoked ExitDisplayModeOnAccessKeyInvoked ExitDisplayModeOnAccessKeyInvoked

Inherited from UIElement

ExitDisplayModeOnAccessKeyInvokedProperty ExitDisplayModeOnAccessKeyInvokedProperty ExitDisplayModeOnAccessKeyInvokedProperty

Inherited from UIElement

FlowDirection FlowDirection FlowDirection

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.

public : FlowDirection FlowDirection { get; set; }
public FlowDirection FlowDirection { get; set; }
Public ReadWrite Property FlowDirection As FlowDirection
<frameworkElement FlowDirection="flowDirectionMemberName"/>

Value
FlowDirection FlowDirection FlowDirection

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.

            <Grid FlowDirection="RightToLeft">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Rectangle Fill="Chartreuse" Width="30" Height="30"/>
                <Rectangle Grid.Row="1" Fill="Purple" Width="30" Height="30"/>
                <Rectangle Grid.Column="1" Fill="Pink" Width="30" Height="30"/>
                <Rectangle Grid.Row="1" Grid.Column="1" Fill="Orange" Width="30" Height="30"/>
            </Grid>

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.

If the FlowDirection value on an object is RightToLeft, certain values and behavior of the FrameworkElement will change:

  • 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.
  • If the FrameworkElement is a Path or other Shape, its visual content is flipped horizontally.
  • 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.

FlowDirection for WebView and WebViewBrush

WebView and WebViewBrush don't promote any right-to-left information to how the HTML is loaded. If there are any left-to-right considerations in the HTML content, consider setting x:Uid directive on the WebView element and specifying any WebView.Source Uniform Resource Identifier (URI) value as a string-form RESW resource. WebView and WebViewBrush also don't inherit FlowDirection from any parent elements. Setting FlowDirection on WebView and WebViewBrush doesn't cause exceptions, but any value you set is ignored by the runtime.

See Also

FlowDirectionProperty FlowDirectionProperty FlowDirectionProperty

Identifies the FlowDirection dependency property.

public : static DependencyProperty FlowDirectionProperty { get; }
public static DependencyProperty FlowDirectionProperty { get; }
Public Static ReadOnly Property FlowDirectionProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The FlowDirection dependency property identifier.

FocusVisualMargin FocusVisualMargin FocusVisualMargin

Gets or sets the outer margin of the focus visual for a FrameworkElement.

public : Thickness FocusVisualMargin { get; set; }
public Thickness FocusVisualMargin { get; set; }
Public ReadWrite Property FocusVisualMargin As Thickness
Value
Thickness Thickness Thickness

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

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Remarks

FocusVisualMargin values greater than 0 apply space outside the ActualWidth and ActualHeight of the object.

Negative values for margin dimensions are permitted, but should be used with caution. Negative margins can cause the content of the object to be clipped.

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

HighVisibility focus visuals are rendered with an outer (primary) and inner (secondary) border. For more info:

FocusVisualMarginProperty FocusVisualMarginProperty FocusVisualMarginProperty

Identifies the FocusVisualMargin dependency property.

public : static DependencyProperty FocusVisualMarginProperty { get; }
public static DependencyProperty FocusVisualMarginProperty { get; }
Public Static ReadOnly Property FocusVisualMarginProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the FocusVisualMargin dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

FocusVisualPrimaryBrush FocusVisualPrimaryBrush FocusVisualPrimaryBrush

Gets or sets the brush used to draw the outer border of a HighVisibility focus visual for a FrameworkElement.

public : Brush FocusVisualPrimaryBrush { get; set; }
public Brush FocusVisualPrimaryBrush { get; set; }
Public ReadWrite Property FocusVisualPrimaryBrush As Brush
Value
Brush Brush Brush

The brush used to draw the outer border of a HighVisibility focus visual.

The default colors are dependent on the RequestedTheme. Typically, the outer (primary) color is solid black, or equivalent, and the inner (secondary) color is solid white, or equivalent.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Remarks

HighVisibility focus visuals are rendered with an outer (primary) and inner (secondary) border. For more info:

FocusVisualPrimaryBrushProperty FocusVisualPrimaryBrushProperty FocusVisualPrimaryBrushProperty

Identifies the FocusVisualPrimaryBrush dependency property.

public : static DependencyProperty FocusVisualPrimaryBrushProperty { get; }
public static DependencyProperty FocusVisualPrimaryBrushProperty { get; }
Public Static ReadOnly Property FocusVisualPrimaryBrushProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the FocusVisualPrimaryBrush dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

FocusVisualPrimaryThickness FocusVisualPrimaryThickness FocusVisualPrimaryThickness

Gets or sets the thickness of the outer border of a HighVisibility focus visual for a FrameworkElement.

public : Thickness FocusVisualPrimaryThickness { get; set; }
public Thickness FocusVisualPrimaryThickness { get; set; }
Public ReadWrite Property FocusVisualPrimaryThickness As Thickness
Value
Thickness Thickness Thickness

The thickness of the outer border of a HighVisibility focus visual. The default value is 2.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Remarks

HighVisibility focus visuals are rendered with an outer (primary) and inner (secondary) border. For more info:

FocusVisualPrimaryThicknessProperty FocusVisualPrimaryThicknessProperty FocusVisualPrimaryThicknessProperty

Identifies the FocusVisualPrimaryThickness dependency property.

public : static DependencyProperty FocusVisualPrimaryThicknessProperty { get; }
public static DependencyProperty FocusVisualPrimaryThicknessProperty { get; }
Public Static ReadOnly Property FocusVisualPrimaryThicknessProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the FocusVisualPrimaryThickness dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

FocusVisualSecondaryBrush FocusVisualSecondaryBrush FocusVisualSecondaryBrush

Gets or sets the brush used to draw the inner border of a HighVisibility focus visual for a FrameworkElement.

public : Brush FocusVisualSecondaryBrush { get; set; }
public Brush FocusVisualSecondaryBrush { get; set; }
Public ReadWrite Property FocusVisualSecondaryBrush As Brush
Value
Brush Brush Brush

The brush used to draw the inner border of a HighVisibility focus visual.

The default colors are dependent on the RequestedTheme. Typically, the outer (primary) color is solid black, or equivalent, and the inner (secondary) color is solid white, or equivalent.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Remarks

HighVisibility focus visuals are rendered with an outer (primary) and inner (secondary) border. For more info:

FocusVisualSecondaryBrushProperty FocusVisualSecondaryBrushProperty FocusVisualSecondaryBrushProperty

Identifies the FocusVisualSecondaryBrush dependency property.

public : static DependencyProperty FocusVisualSecondaryBrushProperty { get; }
public static DependencyProperty FocusVisualSecondaryBrushProperty { get; }
Public Static ReadOnly Property FocusVisualSecondaryBrushProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the FocusVisualSecondaryBrush dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

FocusVisualSecondaryThickness FocusVisualSecondaryThickness FocusVisualSecondaryThickness

Gets or sets the thickness of the inner border of a HighVisibility focus visual for a FrameworkElement.

public : Thickness FocusVisualSecondaryThickness { get; set; }
public Thickness FocusVisualSecondaryThickness { get; set; }
Public ReadWrite Property FocusVisualSecondaryThickness As Thickness
Value
Thickness Thickness Thickness

The thickness of the inner border of a HighVisibility focus visual. The default value is 1.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Remarks

HighVisibility focus visuals are rendered with an outer (primary) and inner (secondary) border. For more info:

FocusVisualSecondaryThicknessProperty FocusVisualSecondaryThicknessProperty FocusVisualSecondaryThicknessProperty

Identifies the FocusVisualSecondaryThickness dependency property.

public : static DependencyProperty FocusVisualSecondaryThicknessProperty { get; }
public static DependencyProperty FocusVisualSecondaryThicknessProperty { get; }
Public Static ReadOnly Property FocusVisualSecondaryThicknessProperty As DependencyProperty
Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

GettingFocusEvent GettingFocusEvent GettingFocusEvent

Inherited from UIElement

Height Height Height

Gets or sets the suggested height of a FrameworkElement.

public : double Height { get; set; }
public double Height { get; set; }
Public ReadWrite Property Height As double
<frameworkElement Height="double"/>
-or-
<frameworkElement Height="Auto"/>
 
Value
double double double

The height, in pixels, of the object. The default is NaN. Except for the special NaN value, this value must be equal to or greater than 0.

Examples

This example shows a simple property set of a UI element that is created at run time and needs initialization of its content and basic display properties such as Height and Width and Background. (Background is actually a Control property, not defined by FrameworkElement.)

Button button2 = new Button();
button2.Height = 50;
button2.Width = 100;
button2.Background = new SolidColorBrush(Colors.Blue);
button2.Content = "Click Me";
Dim button2 As Button = New Button
button2.Height = 50
button2.Width = 100
button2.Background = New SolidColorBrush(Colors.Blue)
button2.Content = "Click Me"

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.

Negative values for Height are not permitted.

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.

See Also

HeightProperty HeightProperty HeightProperty

Identifies the Height dependency property.

public : static DependencyProperty HeightProperty { get; }
public static DependencyProperty HeightProperty { get; }
Public Static ReadOnly Property HeightProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the Height dependency property.

HighContrastAdjustment HighContrastAdjustment HighContrastAdjustment

Inherited from UIElement

HighContrastAdjustmentProperty HighContrastAdjustmentProperty HighContrastAdjustmentProperty

Inherited from UIElement

HoldingEvent HoldingEvent HoldingEvent

Inherited from UIElement

HorizontalAlignment HorizontalAlignment HorizontalAlignment

Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control.

public : HorizontalAlignment HorizontalAlignment { get; set; }
public HorizontalAlignment HorizontalAlignment { get; set; }
Public ReadWrite Property HorizontalAlignment As HorizontalAlignment
<frameworkElement HorizontalAlignment="horizontalAlignmentMemberName"/>
 

Value
HorizontalAlignment HorizontalAlignment HorizontalAlignment

A horizontal alignment setting, as a value of the enumeration. The default is Stretch.

Examples

In this example, the value Center is assigned to HorizontalAlignment and VerticalAlignment, to position the TextBlock elements in the center of the Grid cells.

<Grid x:Name="LayoutRoot" Background="Coral" Width="300" Height="100">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Grid.Row="0" Text="First Name" 
        HorizontalAlignment="Center" VerticalAlignment="Center" />
    <TextBlock Grid.Column="0" Grid.Row="1" Text="Last Name" 
        HorizontalAlignment="Center" VerticalAlignment="Center" />
    <TextBox Grid.Column="1" Grid.Row="0" />
    <TextBox Grid.Column="1" Grid.Row="1" />

</Grid>

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.

In content controls, the control template often uses {TemplateBinding} markup extension expressions to bind the HorizontalContentAlignment property to a HorizontalAlignment property on some element within its template, such as the presenter or the element used as the content area.

See Also

HorizontalAlignmentProperty HorizontalAlignmentProperty HorizontalAlignmentProperty

Identifies the HorizontalAlignment dependency property.

public : static DependencyProperty HorizontalAlignmentProperty { get; }
public static DependencyProperty HorizontalAlignmentProperty { get; }
Public Static ReadOnly Property HorizontalAlignmentProperty As DependencyProperty

IsAccessKeyScope IsAccessKeyScope IsAccessKeyScope

Inherited from UIElement

IsAccessKeyScopeProperty IsAccessKeyScopeProperty IsAccessKeyScopeProperty

Inherited from UIElement

IsDoubleTapEnabled IsDoubleTapEnabled IsDoubleTapEnabled

Inherited from UIElement

IsDoubleTapEnabledProperty IsDoubleTapEnabledProperty IsDoubleTapEnabledProperty

Inherited from UIElement

IsHitTestVisible IsHitTestVisible IsHitTestVisible

Inherited from UIElement

IsHitTestVisibleProperty IsHitTestVisibleProperty IsHitTestVisibleProperty

Inherited from UIElement

IsHoldingEnabled IsHoldingEnabled IsHoldingEnabled

Inherited from UIElement

IsHoldingEnabledProperty IsHoldingEnabledProperty IsHoldingEnabledProperty

Inherited from UIElement

IsRightTapEnabled IsRightTapEnabled IsRightTapEnabled

Inherited from UIElement

IsRightTapEnabledProperty IsRightTapEnabledProperty IsRightTapEnabledProperty

Inherited from UIElement

IsTapEnabled IsTapEnabled IsTapEnabled

Inherited from UIElement

IsTapEnabledProperty IsTapEnabledProperty IsTapEnabledProperty

Inherited from UIElement

KeyDownEvent KeyDownEvent KeyDownEvent

Inherited from UIElement

KeyTipHorizontalOffset KeyTipHorizontalOffset KeyTipHorizontalOffset

Inherited from UIElement

KeyTipHorizontalOffsetProperty KeyTipHorizontalOffsetProperty KeyTipHorizontalOffsetProperty

Inherited from UIElement

KeyTipPlacementMode KeyTipPlacementMode KeyTipPlacementMode

Inherited from UIElement

KeyTipPlacementModeProperty KeyTipPlacementModeProperty KeyTipPlacementModeProperty

Inherited from UIElement

KeyTipVerticalOffset KeyTipVerticalOffset KeyTipVerticalOffset

Inherited from UIElement

KeyTipVerticalOffsetProperty KeyTipVerticalOffsetProperty KeyTipVerticalOffsetProperty

Inherited from UIElement

KeyUpEvent KeyUpEvent KeyUpEvent

Inherited from UIElement

KeyboardAccelerators KeyboardAccelerators KeyboardAccelerators

Inherited from UIElement

Language Language Language

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; }
public string Language { get; set; }
Public ReadWrite Property Language As string
<frameworkElement Language="languageString" .../.
Value
Platform::String string string

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.

The Language property is mainly relevant for these FrameworkElement subclasses:

The TextElement class also has a Language property, and it has similar purpose and behavior for TextElement subclasses such as Run.

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.

See Also

LanguageProperty LanguageProperty LanguageProperty

Identifies the Language dependency property.

public : static DependencyProperty LanguageProperty { get; }
public static DependencyProperty LanguageProperty { get; }
Public Static ReadOnly Property LanguageProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the Language dependency property.

Lights Lights Lights

Inherited from UIElement

LightsProperty LightsProperty LightsProperty

Inherited from UIElement

LosingFocusEvent LosingFocusEvent LosingFocusEvent

Inherited from UIElement

ManipulationCompletedEvent ManipulationCompletedEvent ManipulationCompletedEvent

Inherited from UIElement

ManipulationDeltaEvent ManipulationDeltaEvent ManipulationDeltaEvent

Inherited from UIElement

ManipulationInertiaStartingEvent ManipulationInertiaStartingEvent ManipulationInertiaStartingEvent

Inherited from UIElement

ManipulationMode ManipulationMode ManipulationMode

Inherited from UIElement

ManipulationModeProperty ManipulationModeProperty ManipulationModeProperty

Inherited from UIElement

ManipulationStartedEvent ManipulationStartedEvent ManipulationStartedEvent

Inherited from UIElement

ManipulationStartingEvent ManipulationStartingEvent ManipulationStartingEvent

Inherited from UIElement

Margin Margin Margin

Gets or sets the outer margin of a FrameworkElement.

public : Thickness Margin { get; set; }
public Thickness Margin { get; set; }
Public ReadWrite Property Margin As Thickness
<frameworkElement Margin="uniform"/>
- or -
<frameworkElement Margin="left+right,top+bottom"/>
- or -
<frameworkElement Margin="left,top,right,bottom"/>
 
Value
Thickness Thickness Thickness

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.

    public Page()
    {
        InitializeComponent();
        LayoutDesign();
    }

    private void LayoutDesign()
    {
        //Create Stackpanel for ListBox Control and its description
        StackPanel DeptStackPanel = new StackPanel();
        DeptStackPanel.Margin = new Thickness(10);

        LayoutRoot.Children.Add(DeptStackPanel);
        Grid.SetColumn(DeptStackPanel, 1);
        Grid.SetRow(DeptStackPanel, 1);

        TextBlock DeptListHeading = new TextBlock();
        DeptListHeading.Text = "Department";

        ListBox DeptList = new ListBox();
        DeptList.Items.Add("Finance");
        DeptList.Items.Add("Marketing");
        DeptList.Items.Add("Human Resources");
        DeptList.Items.Add("Payroll");

        DeptStackPanel.Children.Add(DeptListHeading);
        DeptStackPanel.Children.Add(DeptList);

        //Create StackPanel for buttons
        StackPanel ButtonsStackPanel = new StackPanel();
        ButtonsStackPanel.Margin = new Thickness(10);
        ButtonsStackPanel.Orientation = Orientation.Horizontal;
        ButtonsStackPanel.HorizontalAlignment = HorizontalAlignment.Center;

        LayoutRoot.Children.Add(ButtonsStackPanel);
        Grid.SetColumn(ButtonsStackPanel, 0);
        Grid.SetRow(ButtonsStackPanel, 2);
        Grid.SetColumnSpan(ButtonsStackPanel, 2);

        Button BackButton = new Button();
        BackButton.Content = "Back";
        BackButton.Width = 100;

        Button CancelButton = new Button();
        CancelButton.Content = "Cancel";
        CancelButton.Width = 100;

        Button NextButton = new Button();
        NextButton.Content = "Next";
        NextButton.Width = 100;

        ButtonsStackPanel.Children.Add(BackButton);
        ButtonsStackPanel.Children.Add(CancelButton);
        ButtonsStackPanel.Children.Add(NextButton);

        BackButton.Margin = new Thickness(10);
        CancelButton.Margin = new Thickness(10);
        NextButton.Margin = new Thickness(10);
    }
}
Partial Public Class Page
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
        LayoutDesign()
    End Sub

    Private Sub LayoutDesign()
        'Create Stackpanel for ListBox Control and its description 
        Dim DeptStackPanel As New StackPanel()
        DeptStackPanel.Margin = New Thickness(10)

        LayoutRoot.Children.Add(DeptStackPanel)
        Grid.SetColumn(DeptStackPanel, 1)
        Grid.SetRow(DeptStackPanel, 1)

        Dim DeptListHeading As New TextBlock()
        DeptListHeading.Text = "Department"

        Dim DeptList As New ListBox()
        DeptList.Items.Add("Finance")
        DeptList.Items.Add("Marketing")
        DeptList.Items.Add("Human Resources")
        DeptList.Items.Add("Payroll")

        DeptStackPanel.Children.Add(DeptListHeading)
        DeptStackPanel.Children.Add(DeptList)

        'Create StackPanel for buttons 
        Dim ButtonsStackPanel As New StackPanel()
        ButtonsStackPanel.Margin = New Thickness(10)
        ButtonsStackPanel.Orientation = Orientation.Horizontal
        ButtonsStackPanel.HorizontalAlignment = HorizontalAlignment.Center

        LayoutRoot.Children.Add(ButtonsStackPanel)
        Grid.SetColumn(ButtonsStackPanel, 0)
        Grid.SetRow(ButtonsStackPanel, 2)
        Grid.SetColumnSpan(ButtonsStackPanel, 2)

        Dim BackButton As New Button()
        BackButton.Content = "Back"
        BackButton.Height = 30
        BackButton.Width = 100

        Dim CancelButton As New Button()
        CancelButton.Content = "Cancel"
        CancelButton.Height = 30
        CancelButton.Width = 100

        Dim NextButton As New Button()
        NextButton.Content = "Next"
        NextButton.Height = 30
        NextButton.Width = 100

        ButtonsStackPanel.Children.Add(BackButton)
        ButtonsStackPanel.Children.Add(CancelButton)
        ButtonsStackPanel.Children.Add(NextButton)

        BackButton.Margin = New Thickness(10)
        CancelButton.Margin = New Thickness(10)
        NextButton.Margin = New Thickness(10)
    End Sub
End Class

Remarks

Margin behavior and layout

A margin value greater than 0 applies space outside the object's ActualWidth and ActualHeight.

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:

See Also

MarginProperty MarginProperty MarginProperty

Identifies the Margin dependency property.

public : static DependencyProperty MarginProperty { get; }
public static DependencyProperty MarginProperty { get; }
Public Static ReadOnly Property MarginProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The Margin dependency property identifier.

MaxHeight MaxHeight MaxHeight

Gets or sets the maximum height constraint of a FrameworkElement.

public : double MaxHeight { get; set; }
public double MaxHeight { get; set; }
Public ReadWrite Property MaxHeight As double
<frameworkElement MaxHeight="double"/>
 
Value
double double double

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 ).

<Grid Height="600" Width="600">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    
    <StackPanel Grid.Row="0" Grid.Column="0" Margin="5,5,5,5" Orientation="Vertical">
        <TextBlock Text="Stretch" FontWeight="Bold" FontSize="12" />
        <Button Name="btn1" Click="stretchNone" Content="None" />
        <Button Name="btn2" Click="stretchFill" Content="Fill" />
        <Button Name="btn3" Click="stretchUni" Content="Uniform" />
        <Button Name="btn4" Click="stretchUniFill" Content="UniformToFill" />
    </StackPanel>

    <StackPanel Grid.Row="0" Grid.Column="1" Margin="5,5,5,5" Orientation="Vertical">
        <TextBlock Text="StretchDirection" FontWeight="Bold" FontSize="12" />
        <Button Name="btn5" Click="sdUpOnly" Content="UpOnly" />
        <Button Name="btn6" Click="sdDownOnly" Content="DownOnly" />
        <Button Name="btn7" Click="sdBoth" Content="Both" />
    </StackPanel>

    <StackPanel Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Margin="5" 
                Orientation="Vertical">
        <TextBlock Name="txt1" FontSize="12" FontWeight="Bold" />
        <TextBlock Name="txt2" FontSize="12" FontWeight="Bold" />
    </StackPanel>   

    <StackPanel Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Margin="5" 
                Orientation="Horizontal">
        <Viewbox MaxWidth="100" MaxHeight="100" Name="vb1">
            <Image Source="flower.jpg"/>
        </Viewbox>
        <Viewbox MaxWidth="200" MaxHeight="200" Name="vb2">
            <Image Source="flower.jpg"/>
        </Viewbox>
        
        <Viewbox MaxWidth="300" MaxHeight="300" Name="vb3">
            <Image Source="flower.jpg"/>
        </Viewbox>
    </StackPanel>

</Grid>

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.

See Also

MaxHeightProperty MaxHeightProperty MaxHeightProperty

Identifies the MaxHeight dependency property.

public : static DependencyProperty MaxHeightProperty { get; }
public static DependencyProperty MaxHeightProperty { get; }
Public Static ReadOnly Property MaxHeightProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the MaxHeight dependency property.

MaxWidth MaxWidth MaxWidth

Gets or sets the maximum width constraint of a FrameworkElement.

public : double MaxWidth { get; set; }
public double MaxWidth { get; set; }
Public ReadWrite Property MaxWidth As double
<frameworkElement MaxWidth="double"/>
 
Value
double double double

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 ).

<Grid Height="600" Width="600">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    
    <StackPanel Grid.Row="0" Grid.Column="0" Margin="5,5,5,5" Orientation="Vertical">
        <TextBlock Text="Stretch" FontWeight="Bold" FontSize="12" />
        <Button Name="btn1" Click="stretchNone" Content="None" />
        <Button Name="btn2" Click="stretchFill" Content="Fill" />
        <Button Name="btn3" Click="stretchUni" Content="Uniform" />
        <Button Name="btn4" Click="stretchUniFill" Content="UniformToFill" />
    </StackPanel>

    <StackPanel Grid.Row="0" Grid.Column="1" Margin="5,5,5,5" Orientation="Vertical">
        <TextBlock Text="StretchDirection" FontWeight="Bold" FontSize="12" />
        <Button Name="btn5" Click="sdUpOnly" Content="UpOnly" />
        <Button Name="btn6" Click="sdDownOnly" Content="DownOnly" />
        <Button Name="btn7" Click="sdBoth" Content="Both" />
    </StackPanel>

    <StackPanel Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Margin="5" 
                Orientation="Vertical">
        <TextBlock Name="txt1" FontSize="12" FontWeight="Bold" />
        <TextBlock Name="txt2" FontSize="12" FontWeight="Bold" />
    </StackPanel>   

    <StackPanel Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Margin="5" 
                Orientation="Horizontal">
        <Viewbox MaxWidth="100" MaxHeight="100" Name="vb1">
            <Image Source="flower.jpg"/>
        </Viewbox>
        <Viewbox MaxWidth="200" MaxHeight="200" Name="vb2">
            <Image Source="flower.jpg"/>
        </Viewbox>
        
        <Viewbox MaxWidth="300" MaxHeight="300" Name="vb3">
            <Image Source="flower.jpg"/>
        </Viewbox>
    </StackPanel>

</Grid>

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.

See Also

MaxWidthProperty MaxWidthProperty MaxWidthProperty

Identifies the MaxWidth dependency property.

public : static DependencyProperty MaxWidthProperty { get; }
public static DependencyProperty MaxWidthProperty { get; }
Public Static ReadOnly Property MaxWidthProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the MaxWidth dependency property.

MinHeight MinHeight MinHeight

Gets or sets the minimum height constraint of a FrameworkElement.

public : double MinHeight { get; set; }
public double MinHeight { get; set; }
Public ReadWrite Property MinHeight As double
<frameworkElement MinHeight="double"/>
Value
double double double

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.

See Also

MinHeightProperty MinHeightProperty MinHeightProperty

Identifies the MinHeight dependency property.

public : static DependencyProperty MinHeightProperty { get; }
public static DependencyProperty MinHeightProperty { get; }
Public Static ReadOnly Property MinHeightProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the MinHeight dependency property.

MinWidth MinWidth MinWidth

Gets or sets the minimum width constraint of a FrameworkElement.

public : double MinWidth { get; set; }
public double MinWidth { get; set; }
Public ReadWrite Property MinWidth As double
<frameworkElement MinWidth="double"/>
Value
double double double

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.

See Also

MinWidthProperty MinWidthProperty MinWidthProperty

Identifies the MinWidth dependency property.

public : static DependencyProperty MinWidthProperty { get; }
public static DependencyProperty MinWidthProperty { get; }
Public Static ReadOnly Property MinWidthProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the MinWidth dependency property.

Name Name Name

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; }
public string Name { get; set; }
Public ReadWrite Property Name As string
<frameworkElement Name="xamlNameString"/>

Value
Platform::String string string

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.

The value of x:Name or Name is the identifier that you use to identify the source element for an ElementName binding. For more info see Data binding in depth.

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.

See Also

NameProperty NameProperty NameProperty

Identifies the Name dependency property.

public : static DependencyProperty NameProperty { get; }
public static DependencyProperty NameProperty { get; }
Public Static ReadOnly Property NameProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the Name dependency property.

NoFocusCandidateFoundEvent NoFocusCandidateFoundEvent NoFocusCandidateFoundEvent

Inherited from UIElement

Opacity Opacity Opacity

Inherited from UIElement

OpacityProperty OpacityProperty OpacityProperty

Inherited from UIElement

Parent Parent Parent

Gets the parent object of this FrameworkElement in the object tree.

public : DependencyObject Parent { get; }
public DependencyObject Parent { get; }
Public ReadOnly Property Parent As DependencyObject
Value
DependencyObject DependencyObject DependencyObject

The parent object of this object in the object tree.

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.

See Also

PointerCanceledEvent PointerCanceledEvent PointerCanceledEvent

Inherited from UIElement

PointerCaptureLostEvent PointerCaptureLostEvent PointerCaptureLostEvent

Inherited from UIElement

PointerCaptures PointerCaptures PointerCaptures

Inherited from UIElement

PointerCapturesProperty PointerCapturesProperty PointerCapturesProperty

Inherited from UIElement

PointerEnteredEvent PointerEnteredEvent PointerEnteredEvent

Inherited from UIElement

PointerExitedEvent PointerExitedEvent PointerExitedEvent

Inherited from UIElement

PointerMovedEvent PointerMovedEvent PointerMovedEvent

Inherited from UIElement

PointerPressedEvent PointerPressedEvent PointerPressedEvent

Inherited from UIElement

PointerReleasedEvent PointerReleasedEvent PointerReleasedEvent

Inherited from UIElement

PointerWheelChangedEvent PointerWheelChangedEvent PointerWheelChangedEvent

Inherited from UIElement

PreviewKeyDownEvent PreviewKeyDownEvent PreviewKeyDownEvent

Inherited from UIElement

PreviewKeyUpEvent PreviewKeyUpEvent PreviewKeyUpEvent

Inherited from UIElement

Projection Projection Projection

Inherited from UIElement

ProjectionProperty ProjectionProperty ProjectionProperty

Inherited from UIElement

RenderSize RenderSize RenderSize

Inherited from UIElement

RenderTransform RenderTransform RenderTransform

Inherited from UIElement

RenderTransformOrigin RenderTransformOrigin RenderTransformOrigin

Inherited from UIElement

RenderTransformOriginProperty RenderTransformOriginProperty RenderTransformOriginProperty

Inherited from UIElement

RenderTransformProperty RenderTransformProperty RenderTransformProperty

Inherited from UIElement

RequestedTheme RequestedTheme RequestedTheme

Gets or sets the UI theme that is used by the UIElement (and its child elements) for resource determination. The UI theme you specify with RequestedTheme can override the app-level RequestedTheme.

public : ElementTheme RequestedTheme { get; set; }
public ElementTheme RequestedTheme { get; set; }
Public ReadWrite Property RequestedTheme As ElementTheme
<uiElement RequestedTheme="elementThemeMemberName" .../>
Value
ElementTheme ElementTheme ElementTheme

A value of the enumeration, for example Light.

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.

<StackPanel RequestedTheme="Light">
  <TextBlock>Text using light theme.</TextBlock>
  <TextBlock RequestedTheme="Dark">Text using dark theme.</TextBlock>
</StackPanel>

The RequestedTheme property is ignored if the user is running in high contrast mode. See High-contrast themes and XAML high contrast style sample.

Note

On Windows, setting RequestedTheme to ElementTheme.Default will always result in "Dark" being the theme. On Windows Phone, using the ElementTheme.Default value will result in a query for the system theme, as set by the user.

See Also

RequestedThemeProperty RequestedThemeProperty RequestedThemeProperty

Identifies the RequestedTheme dependency property.

public : static DependencyProperty RequestedThemeProperty { get; }
public static DependencyProperty RequestedThemeProperty { get; }
Public Static ReadOnly Property RequestedThemeProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the RequestedTheme dependency property.

Resources Resources Resources

Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement.Resources property element, through XAML implicit collection syntax.

public : ResourceDictionary Resources { get; set; }
public ResourceDictionary Resources { get; set; }
Public ReadWrite Property Resources As ResourceDictionary
<frameworkElement>
  <frameworkElement.Resources>
    oneOrMoreResourceElements
  </frameworkElement.Resources>
</frameworkElement>

Value
ResourceDictionary ResourceDictionary ResourceDictionary

The current locally defined dictionary of resources, where each resource can be accessed by its key.

Examples

This example shows a XAML definition of a simple Resources dictionary that contains one item, a DataTemplate.

<Grid.Resources>
  <DataTemplate x:Key="CBTemplate">
    <Grid>
      <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
      </Grid.ColumnDefinitions>
      <Image Grid.Column="0" Width="50" Height="50" 
        Source="{Binding Photo}" Stretch="Fill"/>
      <TextBlock Grid.Column="1" Text="{Binding Title}" 
        Margin="10" HorizontalAlignment="Left" FontSize="20"/>
    </Grid>
  </DataTemplate>
</Grid.Resources>
<GridView ItemTemplate="{StaticResource CBTemplate}" .../>

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.

void MainPage::SetBGByResource(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
  Button^ b = safe_cast<Windows::UI::Xaml::Controls::Button^>(sender);
  b->Background = safe_cast<Windows::UI::Xaml::Media::Brush^>(this->Resources->Lookup("RainbowBrush"));
}
void SetBGByResource(object sender, RoutedEventArgs e)
{
  Button b = sender as Button;
  b.Background = (Brush)this.Resources["RainbowBrush"];
}
Private Sub SetBGByResource(sender As Object, e As RoutedEventArgs)
    Dim b As Button = TryCast(sender, Button)
    b.Background = DirectCast(Me.Resources("RainbowBrush"), Brush)
End Sub
<Page.Resources>
...

  <LinearGradientBrush x:Key="RainbowBrush">

    <GradientStop Color="Red" Offset="0.05" />

    <GradientStop Color="Orange" Offset="0.23" />

    <GradientStop Color="Yellow" Offset="0.41" />

    <GradientStop Color="Green" Offset="0.59" />

    <GradientStop Color="Blue" Offset="0.77" />

    <GradientStop Color="Purple" Offset="0.95" />

 </LinearGradientBrush>

</Page.Resources>

Remarks

The primary purpose of the items in a Resources collection is to refer to them from other parts of your XAML, using a {StaticResource} markup extension reference (or the similar {ThemeResource} markup extension reference). If you want to access the Resources collection at run time, you can use the API of the relevant template to query, add, or remove items in the ResourceDictionary.

For more info and examples, see ResourceDictionary and XAML resource references.

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 items that you see in a XAML Resources collection are not necessarily the entirety of XAML-defined resources available at runtime. Other resources are available at runtime, due to the influence of the MergedDictionaries property on a ResourceDictionary. The MergedDictionaries value can introduce other dictionaries such as the resources defined by the system, such as resources from the default XAML control templates. Runtime theme-specific resources are also available from the similar ThemeDictionaries property. If you access a Resources collection at runtime and query for a specific key using the Item indexer or Lookup method, you can access and retrieve these resources. For more info, see ResourceDictionary and XAML resource references. Also, Application.Resources can provide resources that are available for any XAML reference in the app and thus extend the resources in any given FrameworkElement.Resources dictionary.

See Also

RightTappedEvent RightTappedEvent RightTappedEvent

Inherited from UIElement

Style Style Style

Gets or sets an instance Style that is applied for this object during layout and rendering.

public : Style Style { get; set; }
public Style Style { get; set; }
Public ReadWrite Property Style As Style
<frameworkElement Style="{StaticResource styleResourceKey}"/>
Value
Style Style Style

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.

See Also

StyleProperty StyleProperty StyleProperty

Identifies the Style dependency property.

public : static DependencyProperty StyleProperty { get; }
public static DependencyProperty StyleProperty { get; }
Public Static ReadOnly Property StyleProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the Style dependency property.

TabFocusNavigation TabFocusNavigation TabFocusNavigation

Inherited from UIElement

TabFocusNavigationProperty TabFocusNavigationProperty TabFocusNavigationProperty

Inherited from UIElement

Tag Tag Tag

Gets or sets an arbitrary object value that can be used to store custom information about this object.

public : Platform::Object Tag { get; set; }
public object Tag { get; set; }
Public ReadWrite Property Tag As object
<frameworkElement>
  <frameworkElement.Tag>
    object*
  </frameworkElement.Tag>
</frameworkElement>
Value
Platform::Object object object

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.

TagProperty TagProperty TagProperty

Identifies the Tag dependency property.

public : static DependencyProperty TagProperty { get; }
public static DependencyProperty TagProperty { get; }
Public Static ReadOnly Property TagProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the Tag dependency property.

TappedEvent TappedEvent TappedEvent

Inherited from UIElement

Transform3D Transform3D Transform3D

Inherited from UIElement

Transform3DProperty Transform3DProperty Transform3DProperty

Inherited from UIElement

Transitions Transitions Transitions

Inherited from UIElement

TransitionsProperty TransitionsProperty TransitionsProperty

Inherited from UIElement

Triggers Triggers Triggers

Gets the collection of triggers for animations that are defined for a FrameworkElement. Not commonly used. See Remarks.

public : TriggerCollection Triggers { get; }
public TriggerCollection Triggers { get; }
Public ReadOnly Property Triggers As TriggerCollection
<frameworkElement>
  <frameworkElement.Triggers>
    oneorMoreTriggers
  </frameworkElement.Triggers>
</frameworkElement>
Value
TriggerCollection TriggerCollection TriggerCollection

The collection of triggers for animations that are defined for this object.

Examples

This XAML example shows the basic structure for using FrameworkElement.Triggers with its default FrameworkElement.Loaded trigger behavior to run a storyboarded animation. This XAML shows the EventTrigger and BeginStoryboard container elements in proper relationship with each using their XAML content property syntax and unnecessary property element tags omitted.

<Canvas Width="200" Height="200" x:Name="animatedcanvas" Background="Red">
    <Canvas.Triggers>
        <EventTrigger>
            <BeginStoryboard>
                <Storyboard x:Name="ColorStoryboard">
                   <!-- Animate the background of the canvas to green over 4 seconds. -->
                    <ColorAnimation Storyboard.TargetName="animatedcanvas"
                      Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
                      To="Green" Duration="0:0:4" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Canvas.Triggers>
</Canvas>

Remarks

Triggers, EventTrigger, Actions and BeginStoryboard are not commonly used. These API mainly exist for compatibility in XAML originally used for Microsoft Silverlight. For most scenarios where event triggers were used previously, you should use built-in animations, visual states, or start animations by writing a Loaded handler that looks up an animation in page-level resources and then calls Begin on the animation's main Storyboard. For more info, see Quickstart: Control templates or Storyboarded animations.

UseLayoutRounding UseLayoutRounding UseLayoutRounding

Inherited from UIElement

UseLayoutRoundingProperty UseLayoutRoundingProperty UseLayoutRoundingProperty

Inherited from UIElement

VerticalAlignment VerticalAlignment VerticalAlignment

Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control.

public : VerticalAlignment VerticalAlignment { get; set; }
public VerticalAlignment VerticalAlignment { get; set; }
Public ReadWrite Property VerticalAlignment As VerticalAlignment
<frameworkElement VerticalAlignment="verticalAlignmentMemberName"/>
Value
VerticalAlignment VerticalAlignment VerticalAlignment

A vertical alignment setting, as a value of the enumeration. The default is Stretch.

Examples

In this example, the value Center is assigned to HorizontalAlignment and VerticalAlignment to position the TextBlock elements in the center of the Grid cells.

<Grid x:Name="LayoutRoot" Background="Coral" Width="300" Height="100">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Grid.Row="0" Text="First Name" 
        HorizontalAlignment="Center" VerticalAlignment="Center" />
    <TextBlock Grid.Column="0" Grid.Row="1" Text="Last Name" 
        HorizontalAlignment="Center" VerticalAlignment="Center" />
    <TextBox Grid.Column="1" Grid.Row="0" />
    <TextBox Grid.Column="1" Grid.Row="1" />

</Grid>

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.

In content controls, the control template often uses {TemplateBinding} markup extension expressions to bind the VerticalContentAlignment property to a VerticalAlignment property on some element within its template, such as the presenter or the element used as the content area.

See Also

VerticalAlignmentProperty VerticalAlignmentProperty VerticalAlignmentProperty

Identifies the VerticalAlignment dependency property.

public : static DependencyProperty VerticalAlignmentProperty { get; }
public static DependencyProperty VerticalAlignmentProperty { get; }
Public Static ReadOnly Property VerticalAlignmentProperty As DependencyProperty

Visibility Visibility Visibility

Inherited from UIElement

VisibilityProperty VisibilityProperty VisibilityProperty

Inherited from UIElement

Width Width Width

Gets or sets the width of a FrameworkElement.

public : double Width { get; set; }
public double Width { get; set; }
Public ReadWrite Property Width As double
<frameworkElement Width="double"/>
-or-
<frameworkElement Width="Auto"/>

Value
double double double

The width of the object, in pixels. The default is NaN. Except for the special NaN value, this value must be equal to or greater than 0.

Examples

This example shows a simple property set of a UI element that is created at run time and needs initialization of its content and basic display properties such as Height and Width and Background. (Background is actually a Control property, not defined by FrameworkElement.)

Button button2 = new Button();
button2.Height = 50;
button2.Width = 100;
button2.Background = new SolidColorBrush(Colors.Blue);
button2.Content = "Click Me";
Dim button2 As Button = New Button
button2.Height = 50
button2.Width = 100
button2.Background = New SolidColorBrush(Colors.Blue)
button2.Content = "Click Me"

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.

Negative values for Width are not permitted.

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.

See Also

WidthProperty WidthProperty WidthProperty

Identifies the Width dependency property.

public : static DependencyProperty WidthProperty { get; }
public static DependencyProperty WidthProperty { get; }
Public Static ReadOnly Property WidthProperty As DependencyProperty
Value
DependencyProperty DependencyProperty DependencyProperty

The identifier for the Width dependency property.

XYFocusDownNavigationStrategy XYFocusDownNavigationStrategy XYFocusDownNavigationStrategy

Inherited from UIElement

XYFocusDownNavigationStrategyProperty XYFocusDownNavigationStrategyProperty XYFocusDownNavigationStrategyProperty

Inherited from UIElement

XYFocusKeyboardNavigation XYFocusKeyboardNavigation XYFocusKeyboardNavigation

Inherited from UIElement

XYFocusKeyboardNavigationProperty XYFocusKeyboardNavigationProperty XYFocusKeyboardNavigationProperty

Inherited from UIElement

XYFocusLeftNavigationStrategy XYFocusLeftNavigationStrategy XYFocusLeftNavigationStrategy

Inherited from UIElement

XYFocusLeftNavigationStrategyProperty XYFocusLeftNavigationStrategyProperty XYFocusLeftNavigationStrategyProperty

Inherited from UIElement

XYFocusRightNavigationStrategy XYFocusRightNavigationStrategy XYFocusRightNavigationStrategy

Inherited from UIElement

XYFocusRightNavigationStrategyProperty XYFocusRightNavigationStrategyProperty XYFocusRightNavigationStrategyProperty

Inherited from UIElement

XYFocusUpNavigationStrategy XYFocusUpNavigationStrategy XYFocusUpNavigationStrategy

Inherited from UIElement

XYFocusUpNavigationStrategyProperty XYFocusUpNavigationStrategyProperty XYFocusUpNavigationStrategyProperty

Inherited from UIElement

Methods

AddHandler(RoutedEvent,Object,Boolean) AddHandler(RoutedEvent,Object,Boolean) AddHandler(RoutedEvent,Object,Boolean)

Inherited from UIElement

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

Inherited from UIElement

ArrangeOverride(Size) ArrangeOverride(Size) ArrangeOverride(Size)

Provides the behavior for the "Arrange" pass of layout. Classes can override this method to define their own "Arrange" pass behavior.

protected : virtual Size ArrangeOverride(Size finalSize)
protected virtual Size ArrangeOverride(Size finalSize)
Protected Overridable Function ArrangeOverride(finalSize As Size) As Size
Parameters
finalSize
Size Size Size

The final area within the parent that this object should use to arrange itself and its children.

Returns

The actual size that is used after the element is arranged in layout.

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.

See Also

CancelDirectManipulations CancelDirectManipulations CancelDirectManipulations

Inherited from UIElement

CapturePointer(Pointer) CapturePointer(Pointer) CapturePointer(Pointer)

Inherited from UIElement

ClearValue(DependencyProperty) ClearValue(DependencyProperty) ClearValue(DependencyProperty)

Inherited from DependencyObject

DeferTree(DependencyObject) DeferTree(DependencyObject) DeferTree(DependencyObject)

Removes the specified element from the XAML visual tree in a way that it can be undeferred later.

public : static void DeferTree(DependencyObject element)
public static void DeferTree(DependencyObject element)
Public Static Function DeferTree(element As DependencyObject) As void
Parameters
element
DependencyObject DependencyObject DependencyObject

The element to remove from the XAML visual tree.

Additional features and requirements
Device family
Windows 10 Creators Update (introduced v10.0.15063.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v4)

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.

FindName(String) FindName(String) FindName(String)

Retrieves an object that has the specified identifier name.

public : Platform::Object FindName(Platform::String name)
public object FindName(String name)
Public Function FindName(name As String) As object
Parameters
name
Platform::String String String

The name of the requested object.

Returns
Platform::Object object object

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 ).

TextElement defines a similar FindName. This enables a FindName behavior in the object model, which is not limited to FrameworkElement. Calls by either implementation of FindName can traverse into a mixed FrameworkElement / text element object tree, and use a common XAML namescope so that a FrameworkElement.FindName call can find a named text element, and vice versa.

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.

See Also

FindSubElementsForTouchTargeting(Point,Rect) FindSubElementsForTouchTargeting(Point,Rect) FindSubElementsForTouchTargeting(Point,Rect)

Inherited from UIElement

GetAnimationBaseValue(DependencyProperty) GetAnimationBaseValue(DependencyProperty) GetAnimationBaseValue(DependencyProperty)

Inherited from DependencyObject

GetBindingExpression(DependencyProperty) GetBindingExpression(DependencyProperty) GetBindingExpression(DependencyProperty)

Returns the BindingExpression that represents the binding on the specified property.

public : BindingExpression GetBindingExpression(DependencyProperty dp)
public BindingExpression GetBindingExpression(DependencyProperty dp)
Public Function GetBindingExpression(dp As DependencyProperty) As BindingExpression
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty

The identifier for the target dependency property to get the binding from.

Returns

A BindingExpression if the target property has an active binding on this object; otherwise, returns null.

GetChildrenInTabFocusOrder GetChildrenInTabFocusOrder GetChildrenInTabFocusOrder

Inherited from UIElement

GetValue(DependencyProperty) GetValue(DependencyProperty) GetValue(DependencyProperty)

Inherited from DependencyObject

GoToElementStateCore(String, Boolean) GoToElementStateCore(String, Boolean) GoToElementStateCore(String, Boolean)

When implemented in a derived class, enables per-state construction of a visual tree for a control template in code, rather than by loading XAML for all states at control startup.

protected : virtual Platform::Boolean GoToElementStateCore(Platform::String stateName, bool useTransitions)
protected virtual bool GoToElementStateCore(String stateName, Boolean useTransitions)
Protected Overridable Function GoToElementStateCore(stateName As String, useTransitions As Boolean) As bool
Parameters
stateName
Platform::String String String

The state to transition to.

useTransitions
bool Boolean Boolean

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
Platform::Boolean bool bool

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.

For general state change logic in a custom control, you should use VisualStateManager.GoToState. The intended scenario for FrameworkElement.GoToElementStateCore is more limited, it's specifically intended for apps or controls that want to optimize the template or logic that creates the visual tree of a ListViewItem or a GridViewItem and presents the contents.

VisualStateManager.GoToState has a slightly different signature because it's a static utility API and uses a control parameter to specify what control to apply state changes to. FrameworkElement.GoToElementStateCore uses the calling object to get this information.

See Also

InvalidateArrange InvalidateArrange InvalidateArrange

Inherited from UIElement

InvalidateMeasure InvalidateMeasure InvalidateMeasure

Inherited from UIElement

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

Inherited from UIElement

MeasureOverride(Size) MeasureOverride(Size) MeasureOverride(Size)

Provides the behavior for the "Measure" pass of the layout cycle. Classes can override this method to define their own "Measure" pass behavior.

protected : virtual Size MeasureOverride(Size availableSize)
protected virtual Size MeasureOverride(Size availableSize)
Protected Overridable Function MeasureOverride(availableSize As Size) As Size
Parameters
availableSize
Size Size Size

The available size that this object can give to child objects. Infinity can be specified as a value to indicate that the object will size to whatever content is available.

Returns

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.
See Also

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()
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.

protected override void OnApplyTemplate()
{
    UpButtonElement = GetTemplateChild("UpButton") as RepeatButton;
    DownButtonElement = GetTemplateChild("DownButton") as RepeatButton;
    TextElement = GetTemplateChild("TextBlock") as TextBlock;

    UpdateStates(false);
}
Protected Overloads Sub OnApplyTemplate()
    UpButtonElement = TryCast(GetTemplateChild("UpButton"), RepeatButton)
    DownButtonElement = TryCast(GetTemplateChild("DownButton"), RepeatButton)
    TextElement = TryCast(GetTemplateChild("TextBlock"), TextBlock)

    UpdateStates(False)
End Sub

Remarks

Although OnApplyTemplate is a method defined by the FrameworkElement class, the OnApplyTemplate behavior and the scenarios for overriding OnApplyTemplate are mainly relevant to a Control subclass. This is because the Template property that you typically define in a XAML file and the internal Windows Runtime logic that applies the templates are specifically for controls. Specialized template behavior also exists for ContentPresenter and ContentControl.

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.
See Also

OnCreateAutomationPeer OnCreateAutomationPeer OnCreateAutomationPeer

Inherited from UIElement

OnDisconnectVisualChildren OnDisconnectVisualChildren OnDisconnectVisualChildren

Inherited from UIElement

OnProcessKeyboardAccelerators(ProcessKeyboardAcceleratorEventArgs) OnProcessKeyboardAccelerators(ProcessKeyboardAcceleratorEventArgs) OnProcessKeyboardAccelerators(ProcessKeyboardAcceleratorEventArgs)

Inherited from UIElement

ReadLocalValue(DependencyProperty) ReadLocalValue(DependencyProperty) ReadLocalValue(DependencyProperty)

Inherited from DependencyObject

RegisterPropertyChangedCallback(DependencyProperty,DependencyPropertyChangedCallback) RegisterPropertyChangedCallback(DependencyProperty,DependencyPropertyChangedCallback) RegisterPropertyChangedCallback(DependencyProperty,DependencyPropertyChangedCallback)

Inherited from DependencyObject

ReleasePointerCapture(Pointer) ReleasePointerCapture(Pointer) ReleasePointerCapture(Pointer)

Inherited from UIElement

ReleasePointerCaptures ReleasePointerCaptures ReleasePointerCaptures

Inherited from UIElement

RemoveHandler(RoutedEvent,Object) RemoveHandler(RoutedEvent,Object) RemoveHandler(RoutedEvent,Object)

Inherited from UIElement

SetBinding(DependencyProperty, BindingBase) SetBinding(DependencyProperty, BindingBase) SetBinding(DependencyProperty, BindingBase)

Attaches a binding to a FrameworkElement, using the provided binding object

.

public : void SetBinding(DependencyProperty dp, BindingBase binding)
public void SetBinding(DependencyProperty dp, BindingBase binding)
Public Function SetBinding(dp As DependencyProperty, binding As BindingBase) As void
Parameters
dp
DependencyProperty DependencyProperty DependencyProperty

The dependency property identifier of the property that is data bound.

binding
BindingBase BindingBase BindingBase

The binding to use for the property.

Examples

This example establishes a binding to a dependency property on an object by calling SetBinding.

// Create the source string.
string s = "Hello";

// Create the binding description.
Binding b = new Binding();
b.Mode = BindingMode.OneTime;
b.Source = s;

// Attach the binding to the target.
MyText.SetBinding(TextBlock.TextProperty, b);
'Create the source string 
Dim s As String = "Hello"

'Create the binding description 
Dim b As New Binding()
b.Mode = BindingMode.OneTime
b.Source = s

'Attach the binding to the target 
MyText.SetBinding(TextBlock.TextProperty, b)

Remarks

This method is a convenience method that calls BindingOperations.SetBinding, passing the current instance as the target parameter.

The type of the binding parameter is BindingBase for compatibility reasons, but in the Windows Runtime you always pass a Binding instance. Binding is derived from BindingBase.

The dp parameter takes a dependency property identifier. For more info on dependency properties and how a DependencyProperty value serves as the identifier, see Dependency properties overview.

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.

Note

Calling the SetBinding method and passing in a new Binding object won't necessarily remove an existing binding. Instead, you should first call the DependencyObject.ClearValue method, then call SetBinding.

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.

See Also

SetValue(DependencyProperty,Object) SetValue(DependencyProperty,Object) SetValue(DependencyProperty,Object)

Inherited from DependencyObject

StartBringIntoView StartBringIntoView StartBringIntoView

Inherited from UIElement

StartBringIntoView(BringIntoViewOptions) StartBringIntoView(BringIntoViewOptions) StartBringIntoView(BringIntoViewOptions)

Inherited from UIElement

StartDragAsync(PointerPoint) StartDragAsync(PointerPoint) StartDragAsync(PointerPoint)

Inherited from UIElement

TransformToVisual(UIElement) TransformToVisual(UIElement) TransformToVisual(UIElement)

Inherited from UIElement

TryInvokeKeyboardAccelerator(ProcessKeyboardAcceleratorEventArgs) TryInvokeKeyboardAccelerator(ProcessKeyboardAcceleratorEventArgs) TryInvokeKeyboardAccelerator(ProcessKeyboardAcceleratorEventArgs)

Inherited from UIElement

TryStartDirectManipulation(Pointer) TryStartDirectManipulation(Pointer) TryStartDirectManipulation(Pointer)

Inherited from UIElement

UnregisterPropertyChangedCallback(DependencyProperty,Int64) UnregisterPropertyChangedCallback(DependencyProperty,Int64) UnregisterPropertyChangedCallback(DependencyProperty,Int64)

Inherited from DependencyObject

UpdateLayout UpdateLayout UpdateLayout

Inherited from UIElement

Events

AccessKeyDisplayDismissed AccessKeyDisplayDismissed AccessKeyDisplayDismissed

Inherited from UIElement

AccessKeyDisplayRequested AccessKeyDisplayRequested AccessKeyDisplayRequested

Inherited from UIElement

AccessKeyInvoked AccessKeyInvoked AccessKeyInvoked

Inherited from UIElement

ActualThemeChanged ActualThemeChanged ActualThemeChanged

Occurs when the ActualTheme property value has changed.

public : event TypedEventHandler ActualThemeChanged<FrameworkElement, object>
public event TypedEventHandler ActualThemeChanged<FrameworkElement, object>
Public Event TypedEventHandler ActualThemeChanged( Of ( Of FrameworkElement ), ( Of object ))
<frameworkElement ActualTheme="eventhandler"/>

Additional features and requirements
Device family
Windows 10 Fall Creators Update (introduced v10.0.16299.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v5)

CharacterReceived CharacterReceived CharacterReceived

Inherited from UIElement

ContextCanceled ContextCanceled ContextCanceled

Inherited from UIElement

ContextRequested ContextRequested ContextRequested

Inherited from UIElement

DataContextChanged DataContextChanged DataContextChanged

Occurs when the value of the FrameworkElement.DataContext property changes.

public : event TypedEventHandler DataContextChanged<FrameworkElement, DataContextChangedEventArgs>
public event TypedEventHandler DataContextChanged<FrameworkElement, DataContextChangedEventArgs>
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.

See Also

DoubleTapped DoubleTapped DoubleTapped

Inherited from UIElement

DragEnter DragEnter DragEnter

Inherited from UIElement

DragLeave DragLeave DragLeave

Inherited from UIElement

DragOver DragOver DragOver

Inherited from UIElement

DragStarting DragStarting DragStarting

Inherited from UIElement

Drop Drop Drop

Inherited from UIElement

DropCompleted DropCompleted DropCompleted

Inherited from UIElement

GettingFocus GettingFocus GettingFocus

Inherited from UIElement

GotFocus GotFocus GotFocus

Inherited from UIElement

Holding Holding Holding

Inherited from UIElement

KeyDown KeyDown KeyDown

Inherited from UIElement

KeyUp KeyUp KeyUp

Inherited from UIElement

LayoutUpdated LayoutUpdated LayoutUpdated

Occurs when the layout of the visual tree changes, due to layout-relevant properties changing value or some other action that refreshes the layout.

public : event EventHandler LayoutUpdated<Platform::Object>
public event EventHandler LayoutUpdated<object>
Public Event EventHandler LayoutUpdated( Of ( Of object ))
<frameworkElement LayoutUpdated="eventhandler"/>
 

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.

See Also

Loaded Loaded Loaded

Occurs when a FrameworkElement has been constructed and added to the object tree, and is ready for interaction.

public : event RoutedEventHandler Loaded<>
public event RoutedEventHandler Loaded<>
Public Event RoutedEventHandler Loaded( Of )
<frameworkElement Loaded="eventhandler"/>
 

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.

            this.Page.Loaded += (sender, e) =>
            {
                // Keyboard and mouse navigation only apply when occupying the entire window
                if (this.Page.ActualHeight == Window.Current.Bounds.Height &&
                    this.Page.ActualWidth == Window.Current.Bounds.Width)
                {
                    // Listen to the window directly so focus isn't required
                    Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
                        CoreDispatcher_AcceleratorKeyActivated;
                    Window.Current.CoreWindow.PointerPressed +=
                        this.CoreWindow_PointerPressed;
                }
            };

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.

// Start the animation when the object loads
void SampleApp::Page::Start_Animation(Platform::Object^ sender, Windows::UI::Xaml::Input::RoutedEventArgs^ e)
{
    myStoryboard->Begin();
}
<Canvas Width="450" Height="350">
    <Canvas.Resources>
        <Storyboard x:Name="myStoryboard">

            <!-- Animate the center point of the ellipse from 100 X, 300 Y
             to 400 X, 100 Y over 5 seconds. -->
            <PointAnimation
             Storyboard.TargetProperty="Center"
             Storyboard.TargetName="MyAnimatedEllipseGeometry"
             Duration="0:0:5" 
             From="100,300"
             To="400,100"
             RepeatBehavior="Forever" EnableDependentAnimation="True"/>

        </Storyboard>
    </Canvas.Resources>
    <Path Fill="Blue" Loaded="Start_Animation">
        <Path.Data>

            <!-- Describes an ellipse. -->
            <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
             Center="200,100" RadiusX="15" RadiusY="15" />
        </Path.Data>
    </Path>
</Canvas>
' Start the animation when the object loads
Private Sub Start_Animation(ByVal sender As Object, ByVal e As EventArgs)
    myStoryboard.Begin()
End Sub
<Canvas Width="400" Height="300">
    <Canvas.Resources>
        <Storyboard x:Name="myStoryboard">

            <!-- Animating the Center property uses 3 KeyFrames, which animate
             the ellipse allong a triangular path. -->
            <PointAnimationUsingKeyFrames
          Storyboard.TargetProperty="Center"
          Storyboard.TargetName="MyAnimatedEllipseGeometry"
          Duration="0:0:5" RepeatBehavior="Forever" EnableDependentAnimation="True">

                <!-- Over the first half second, Using a LinearPointKeyFrame, the ellipse 
               moves steadily from its starting position along the first line of the 
               trianglar path.  -->
                <LinearPointKeyFrame KeyTime="0:0:0.5" Value="100,300" />

                <!-- Using a DiscretePointKeyFrame, the ellipse suddenly changes position
               after the first second of the animation. -->
                <DiscretePointKeyFrame KeyTime="0:0:1" Value="400,300" />

                <!-- Using a SplinePointKeyFrame, the ellipse moves back to its starting
               position. It moves slowly at first and then speeds up. This key frame 
               takes 2 seconds to complete. -->
                <SplinePointKeyFrame KeySpline="0.6,0.0 0.9,0.00" 
                 KeyTime="0:0:3" Value="200,100" />
            </PointAnimationUsingKeyFrames>
        </Storyboard>
    </Canvas.Resources>
    <Path Fill="Blue" Loaded="Start_Animation">
        <Path.Data>

            <!-- Describes an ellipse. -->
            <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
             Center="200,100" RadiusX="15" RadiusY="15" />
        </Path.Data>
    </Path>
</Canvas>
' Start the animation when the object loads
Private Sub Start_Animation(ByVal sender As Object, ByVal e As EventArgs)
    myStoryboard.Begin()
End Sub
// Start the animation when the object loads
void SampleApp::Page::Start_Animation(Platform::Object^ sender, Windows::UI::Xaml::Input::RoutedEventArgs^ e)
{
    myStoryboard->Begin();
}
// Start the animation when the object loads
private void Start_Animation(object sender, RoutedEventArgs e)
{
    myStoryboard.Begin();
}
' Start the animation when the object loads
Private Sub Start_Animation(ByVal sender As Object, ByVal e As EventArgs)
    myStoryboard.Begin()
End Sub

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.

See Also

Loading Loading Loading

Occurs when a FrameworkElement begins to load.

public : event TypedEventHandler Loading<FrameworkElement, object>
public event TypedEventHandler Loading<FrameworkElement, object>
Public Event TypedEventHandler Loading( Of ( Of FrameworkElement ), ( Of object ))
<frameworkElement Loading="eventhandler"/>
 

LosingFocus LosingFocus LosingFocus

Inherited from UIElement

LostFocus LostFocus LostFocus

Inherited from UIElement

ManipulationCompleted ManipulationCompleted ManipulationCompleted

Inherited from UIElement

ManipulationDelta ManipulationDelta ManipulationDelta

Inherited from UIElement

ManipulationInertiaStarting ManipulationInertiaStarting ManipulationInertiaStarting

Inherited from UIElement

ManipulationStarted ManipulationStarted ManipulationStarted

Inherited from UIElement

ManipulationStarting ManipulationStarting ManipulationStarting

Inherited from UIElement

NoFocusCandidateFound NoFocusCandidateFound NoFocusCandidateFound

Inherited from UIElement

PointerCanceled PointerCanceled PointerCanceled

Inherited from UIElement

PointerCaptureLost PointerCaptureLost PointerCaptureLost

Inherited from UIElement

PointerEntered PointerEntered PointerEntered

Inherited from UIElement

PointerExited PointerExited PointerExited

Inherited from UIElement

PointerMoved PointerMoved PointerMoved

Inherited from UIElement

PointerPressed PointerPressed PointerPressed

Inherited from UIElement

PointerReleased PointerReleased PointerReleased

Inherited from UIElement

PointerWheelChanged PointerWheelChanged PointerWheelChanged

Inherited from UIElement

PreviewKeyDown PreviewKeyDown PreviewKeyDown

Inherited from UIElement

PreviewKeyUp PreviewKeyUp PreviewKeyUp

Inherited from UIElement

ProcessKeyboardAccelerators ProcessKeyboardAccelerators ProcessKeyboardAccelerators

Inherited from UIElement

RightTapped RightTapped RightTapped

Inherited from UIElement

SizeChanged SizeChanged SizeChanged

Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement.

public : event SizeChangedEventHandler SizeChanged<>
public event SizeChangedEventHandler SizeChanged<>
Public Event SizeChangedEventHandler SizeChanged( Of )
<frameworkElement SizeChanged="eventhandler"/>

Remarks

SizeChanged fires whenever the size (either ActualHeight or ActualWidth ) has changed on the object, which is after the Measure and Arrange passes are complete.

The SizeChangedEventArgs event data for the SizeChanged event provides two properties: the PreviousSize value, representing the size of the element before the layout change happened, and the NewSize value, representing the current size. To get the height and width info use the Height and Width values of the Size structure value for these SizeChangedEventArgs properties within your event handler.

One reason to handle the SizeChanged event is to see whether the ratio of an element's ActualHeight versus ActualWidth have changed, because of a new layout. For example, this might happen if the user has resized the app window and the overall app view is now a narrow view. For more info on this scenario, see Quickstart: Designing apps for different window sizes or Layout for windows that are taller than wide sample.

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:

  • Code that adjusts the Height and Width of that element specifically.
  • Code that changes the constraint properties (like MinHeight or MaxHeight affecting the ActualHeight ).
  • 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.
  • ApplicationView changes or DisplayInformation changes that ultimately affect the window and page dimensions, and potentially all the UI elements within.

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.

See Also

Tapped Tapped Tapped

Inherited from UIElement

Unloaded Unloaded Unloaded

Occurs when this object is no longer connected to the main object tree.

public : event RoutedEventHandler Unloaded<>
public event RoutedEventHandler Unloaded<>
Public Event RoutedEventHandler Unloaded( Of )
<frameworkElement Unloaded="eventhandler"/>

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.

See Also