Partager via


Application.LoadComponent Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Loads a XAML file that is located at the specified Uniform Resource Identifier (URI) and converts it to an instance of the object that is specified by the root element of the XAML file.

Namespace:  System.Windows
Assembly:  System.Windows (in System.Windows.dll)

Syntax

'Declaration
<SecuritySafeCriticalAttribute> _
Public Shared Sub LoadComponent ( _
    component As Object, _
    resourceLocator As Uri _
)
[SecuritySafeCriticalAttribute]
public static void LoadComponent(
    Object component,
    Uri resourceLocator
)

Parameters

  • component
    Type: System.Object
    An object of the same type as the root element of the XAML file to be loaded.
  • resourceLocator
    Type: System.Uri
    A relative URI that identifies the XAML file to be loaded.

Exceptions

Exception Condition
ArgumentException

resourceLocator is an absolute URI.

ArgumentNullException

component is nulla null reference (Nothing in Visual Basic).

-or-

resourceLocator is nulla null reference (Nothing in Visual Basic).

XamlParseException

An error occurred while parsing the XAML file.

Remarks

The XAML file that is loaded can be either an application definition file (App.xaml, for example) or a page file (MainPage.xaml, for example). The XAML file can be in one of the following locations:

  • Included in the application package.

  • Embedded in the application assembly.

  • Embedded within a library assembly at the site of origin.

Examples

The following code example demonstrates how to use this method to merge the XAML and code-behind portions of a Page class. This code is similar to the InitializeComponent method that Visual Studio generates for the same purpose.

Visual Studio generates the InitializeComponent method when a XAML file has a build action of Page. To load a XAML file using the following example code, set its build action to Resource.

Private LayoutRoot As System.Windows.Controls.Grid

Public Sub New()
    System.Windows.Application.LoadComponent(Me, New System.Uri( _
        "/SilverlightApplication1;component/Page.xaml", _
        System.UriKind.Relative))
    Me.LayoutRoot = CType(Me.FindName("LayoutRoot"),  _
        System.Windows.Controls.Grid)
End Sub
private System.Windows.Controls.Grid LayoutRoot;

public Page()
{
    System.Windows.Application.LoadComponent(this, new System.Uri(
        "/SilverlightApplication1;component/Page.xaml", 
        System.UriKind.Relative));
    this.LayoutRoot = ((System.Windows.Controls.Grid)
        (this.FindName("LayoutRoot")));
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.