FrameworkElement FrameworkElement FrameworkElement Class

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.

Syntax

Declaration

public class FrameworkElementpublic class FrameworkElementPublic Class FrameworkElement

Inheritance Hierarchy

Inherited Members

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

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(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase), GetBindingExpression(Windows.UI.Xaml.DependencyProperty).

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(System.String), 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 Windows Store 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:

Properties summary

Gets the rendered height of a FrameworkElement. See Remarks.

Identifies the ActualHeight dependency property. See Remarks.

Gets the rendered width of a FrameworkElement. See Remarks.

Identifies the ActualWidth dependency property. See Remarks.

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

Identifies for the AllowFocusOnInteraction dependency property.

Gets or sets whether a disabled control can receive focus.

Identifies the AllowFocusWhenDisabled dependency property.

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.

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

Identifies the DataContext dependency property.

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.

Identifies the FlowDirection dependency property.

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

Identifies the FocusVisualMargin dependency property.

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

Identifies the FocusVisualPrimaryBrush dependency property.

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

Identifies the FocusVisualPrimaryThickness dependency property.

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

Identifies the FocusVisualSecondaryBrush dependency property.

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

Identifies the FocusVisualSecondaryThickness dependency property.

Gets or sets the suggested height of a FrameworkElement.

Identifies the Height dependency property.

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.

Identifies the HorizontalAlignment dependency property.

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.

Identifies the Language dependency property.

Gets or sets the outer margin of a FrameworkElement.

Identifies the Margin dependency property.

Gets or sets the maximum height constraint of a FrameworkElement.

Identifies the MaxHeight dependency property.

Gets or sets the maximum width constraint of a FrameworkElement.

Identifies the MaxWidth dependency property.

Gets or sets the minimum height constraint of a FrameworkElement.

Identifies the MinHeight dependency property.

Gets or sets the minimum width constraint of a FrameworkElement.

Identifies the MinWidth dependency property.

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.

Identifies the Name dependency property.

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

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.

Identifies the RequestedTheme dependency property.

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.

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

Identifies the Style dependency property.

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

Identifies the Tag dependency property.

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

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.

Identifies the VerticalAlignment dependency property.

Gets or sets the width of a FrameworkElement.

Identifies the Width dependency property.

Methods summary

Retrieves an object that has the specified identifier name.

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

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

.

Events summary

Occurs when the value of the DataContext property changes.

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

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

Occurs when a FrameworkElement begins to load.

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

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

Properties

  • ActualHeight
    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

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

    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.

    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
    
  • ActualHeightProperty
    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

    Property Value

    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.

  • ActualWidth
    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

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

  • ActualWidthProperty
    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

    Property Value

    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.

  • AllowFocusOnInteraction
    AllowFocusOnInteraction
    AllowFocusOnInteraction
    AllowFocusOnInteraction

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

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

    Property Value

    • bool
      bool
      bool

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

  • AllowFocusOnInteractionProperty
    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

    Property Value

  • AllowFocusWhenDisabled
    AllowFocusWhenDisabled
    AllowFocusWhenDisabled
    AllowFocusWhenDisabled

    Gets or sets whether a disabled control can receive focus.

    public bool AllowFocusWhenDisabled { get; set; }public bool AllowFocusWhenDisabled { get; set; }Public ReadWrite Property AllowFocusWhenDisabled As bool

    Property Value

    • bool
      bool
      bool

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

  • AllowFocusWhenDisabledProperty
    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

    Property Value

  • BaseUri
    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

    Property Value

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

    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.

    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
    
  • DataContext
    DataContext
    DataContext
    DataContext

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

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

    Property Value

    • object
      object
      object

      The object to use as data context.

    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<T> or List<T>), or derive from ObservableCollection<T>.

    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
    
  • DataContextProperty
    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

    Property Value

  • FlowDirection
    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"/>
    
    

    Property Value

    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(Windows.Foundation.Point,Windows.UI.Xaml.UIElement).
    • 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 ColumnDefinitions 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 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.

    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>
    
  • FlowDirectionProperty
    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

    Property Value

  • FocusVisualMargin
    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

    Property Value

    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.

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

  • FocusVisualMarginProperty
    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

    Property Value

  • FocusVisualPrimaryBrush
    FocusVisualPrimaryBrush
    FocusVisualPrimaryBrush
    FocusVisualPrimaryBrush

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

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

    Property Value

    • The brush used to draw the outer border of a FocusVisualKind 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.

    Remarks

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

  • FocusVisualPrimaryBrushProperty
    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

    Property Value

  • FocusVisualPrimaryThickness
    FocusVisualPrimaryThickness
    FocusVisualPrimaryThickness
    FocusVisualPrimaryThickness

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

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

    Property Value

    Remarks

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

  • FocusVisualPrimaryThicknessProperty
    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

    Property Value

  • FocusVisualSecondaryBrush
    FocusVisualSecondaryBrush
    FocusVisualSecondaryBrush
    FocusVisualSecondaryBrush

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

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

    Property Value

    • The brush used to draw the inner border of a FocusVisualKind 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.

    Remarks

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

  • FocusVisualSecondaryBrushProperty
    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

    Property Value

  • FocusVisualSecondaryThickness
    FocusVisualSecondaryThickness
    FocusVisualSecondaryThickness
    FocusVisualSecondaryThickness

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

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

    Property Value

    Remarks

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

  • FocusVisualSecondaryThicknessProperty
    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

    Property Value

  • Height
    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"/>
     
    

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

    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.

    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 @Windows.UI.Xaml.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"
    
  • HeightProperty
    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

    Property Value

  • HorizontalAlignment
    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"/>
     
    
    

    Property Value

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

    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>
    
  • HorizontalAlignmentProperty
    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

    Property Value

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

    Property Value

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

  • LanguageProperty
    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

    Property Value

  • Margin
    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"/>
     
    

    Property Value

    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:

    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
    
  • MarginProperty
    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

    Property Value

  • MaxHeight
    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"/>
     
    

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

    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.

    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>
    
  • MaxHeightProperty
    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

    Property Value

  • MaxWidth
    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"/>
     
    

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

    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.

    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>
    
  • MaxWidthProperty
    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

    Property Value

  • MinHeight
    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"/>
    

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

  • MinHeightProperty
    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

    Property Value

  • MinWidth
    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"/>
    

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

  • MinWidthProperty
    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

    Property Value

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

    Property Value

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

    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 Load(System.String) 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 TargetNameProperty 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(System.String), 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(System.String) searches the XAML-created object tree in its entirety. Technically, what FindName(System.String) 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(System.String) cannot find names that are defined in applied templates. To find items in applied templates, use GetChild(Windows.UI.Xaml.DependencyObject,System.Int32) to get the applied template root object. Then you can call FindName(System.String) 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(System.String) 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(System.String) 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.

    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 TargetNameProperty 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
    
  • NameProperty
    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

    Property Value

  • Parent
    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

    Property Value

    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 Windows Store 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.

  • RequestedTheme
    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" .../>
    

    Property Value

    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 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.xaml <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 will always result in "Dark" being the theme. On Windows Phone, using the ElementTheme value will result in a query for the system theme, as set by the user.

  • RequestedThemeProperty
    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

    Property Value

  • Resources
    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>
    

    Property Value

    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<K, V> 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(System.Object) method, you can access and retrieve these resources. For more info, see ResourceDictionary and XAML resource references. Also, Resources can provide resources that are available for any XAML reference in the app and thus extend the resources in any given Resources dictionary.

    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>
    
  • Style
    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}"/>
    

    Property Value

    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.

  • StyleProperty
    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

    Property Value

  • Tag
    Tag
    Tag
    Tag

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

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

    Property Value

    • 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
    TagProperty

    Identifies the Tag dependency property.

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

    Property Value

  • Triggers
    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>
    

    Property Value

    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.

    Examples

    This XAML example shows the basic structure for using Triggers with its default 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>
    
  • VerticalAlignment
    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"/>
    

    Property Value

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

    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>
    
  • VerticalAlignmentProperty
    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

    Property Value

  • Width
    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"/>
    

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

    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.

    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 @Windows.UI.Xaml.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"
    
  • WidthProperty
    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

    Property Value

Methods

  • FindName(System.String)
    FindName(System.String)
    FindName(System.String)
    FindName(System.String)

    Retrieves an object that has the specified identifier name.

    public object FindName(System.String)public object FindName(System.String)Public Function FindName(System.String) As object

    Parameters

    • name
      System.String
      System.String
      System.String

      The name of the requested object.

    Returns

    • 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(System.String) 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(System.String) in your Windows Runtime code will be from within the generated InitializeComponent call for a XAML page. In this situation, FindName(System.String) 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(System.String) 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(System.String) 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 Load(System.String) and subsequently added to the object tree.

    If you return an unexpected null result for FindName(System.String), 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 on the control to get the control's applied template root, and call FindName(System.String) specifically on the template root to access elements that are named within the template XAML.
    • For the Load(System.String) case, you should preserve a reference to the return value of the Load(System.String) call, which is an object that will become the owner or basis of the created XAML namescope that is relevant. Then call FindName(System.String) from that scope instead.

    The object returned by FindName(System.String) 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(System.String). 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 FindName(System.String) 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(System.String) from within that XAML namescope can find and return the code-created object.

  • GetBindingExpression(Windows.UI.Xaml.DependencyProperty)
    GetBindingExpression(Windows.UI.Xaml.DependencyProperty)
    GetBindingExpression(Windows.UI.Xaml.DependencyProperty)
    GetBindingExpression(Windows.UI.Xaml.DependencyProperty)

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

    public BindingExpression GetBindingExpression(Windows.UI.Xaml.DependencyProperty)public BindingExpression GetBindingExpression(Windows.UI.Xaml.DependencyProperty)Public Function GetBindingExpression(Windows.UI.Xaml.DependencyProperty) As BindingExpression

    Parameters

    Returns

  • SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase)
    SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase)
    SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase)
    SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase)

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

    .

    public void SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase)public void SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase)Public Function SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase) As void

    Parameters

    Remarks

    This method is a convenience method that calls SetBinding(Windows.UI.Xaml.DependencyObject,Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase), 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(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase) method and passing in a new Binding object won't necessarily remove an existing binding. Instead, you should first call the ClearValue(Windows.UI.Xaml.DependencyProperty) method, then call SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase).

    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 RowDefinitions 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 RowDefinitions example, that identifier is 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.

    Examples

    This example establishes a binding to a dependency property on an object by calling SetBinding(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.Data.BindingBase).

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

Events

  • DataContextChanged
    DataContextChanged
    DataContextChanged
    DataContextChanged

    Occurs when the value of the DataContext property changes.

    public event TypedEventHandler DataContextChangedpublic event TypedEventHandler DataContextChangedPublic Event DataContextChanged

    Remarks

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

  • LayoutUpdated
    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 LayoutUpdatedpublic event EventHandler LayoutUpdatedPublic Event LayoutUpdated
    <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.

  • Loaded
    Loaded
    Loaded
    Loaded

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

    public event RoutedEventHandler Loadedpublic event RoutedEventHandler LoadedPublic Event Loaded
    <frameworkElement Loaded="eventhandler"/>
     
    

    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 GoToState(Windows.UI.Xaml.Controls.Control,System.String,System.Boolean) 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(System.String) 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(System.String) 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(System.String).

    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.

    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
    
  • Loading
    Loading
    Loading
    Loading

    Occurs when a FrameworkElement begins to load.

    public event TypedEventHandler Loadingpublic event TypedEventHandler LoadingPublic Event Loading
    <frameworkElement Loading="eventhandler"/>
     
    
  • SizeChanged
    SizeChanged
    SizeChanged
    SizeChanged

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

    public event SizeChangedEventHandler SizeChangedpublic event SizeChangedEventHandler SizeChangedPublic Event SizeChanged
    <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 (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.

  • Unloaded
    Unloaded
    Unloaded
    Unloaded

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

    public event RoutedEventHandler Unloadedpublic event RoutedEventHandler UnloadedPublic Event Unloaded
    <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.

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ComposableAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.ThreadingAttribute
Windows.Foundation.Metadata.WebHostHiddenAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.StaticAttribute

Details

Assembly

Windows.UI.Xaml.dll