Aracılığıyla paylaş


DataTemplate Class

Definition

Describes the visual structure of a data object. Use data binding for specific elements in the template that display the data values.

/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class DataTemplate : FrameworkTemplate
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class DataTemplate : FrameworkTemplate, IElementFactory
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public class DataTemplate : FrameworkTemplate
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public class DataTemplate : FrameworkTemplate, IElementFactory
Public Class DataTemplate
Inherits FrameworkTemplate
Public Class DataTemplate
Inherits FrameworkTemplate
Implements IElementFactory
<DataTemplate ...>
  templateContent
</DataTemplate>
 

Inheritance
Object IInspectable DependencyObject FrameworkTemplate DataTemplate
Attributes
Implements

Windows requirements

Device family
Windows 10 (introduced in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v1.0)

Examples

The following example uses a DataTemplate to display the items of a ListBox. In this example, the ListBox is bound to a collection of Customer objects. The DataTemplate contains TextBlock controls that bind to the FirstName, LastName, and Address properties. For more info on data binding, see Data binding in depth.

<Grid>
    <Grid.Resources>
        <src:Customers x:Key="customers"/>
    </Grid.Resources>

    <ListBox ItemsSource="{StaticResource customers}" Width="350" Margin="0,5,0,10">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Padding="5,0,5,0"
          Text="{Binding FirstName}" />
                    <TextBlock Text="{Binding LastName}" />
                    <TextBlock Text=", " />
                    <TextBlock Text="{Binding Address}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>
public class Customer
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String Address { get; set; }

    public Customer(String firstName, String lastName, String address)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
    }

}

public class Customers : ObservableCollection<Customer>
{
    public Customers()
    {
        Add(new Customer("Michael", "Anderberg",
                "12 North Third Street, Apartment 45"));
        Add(new Customer("Chris", "Ashton",
                "34 West Fifth Street, Apartment 67"));
        Add(new Customer("Seo-yun", "Jun",
                "56 East Seventh Street, Apartment 89"));
        Add(new Customer("Guido", "Pica",
                "78 South Ninth Street, Apartment 10"));
    }

}
Public Class Customer
    Private _firstName As String
    Private _lastName As String
    Private _address As String

    Public Property FirstName() As String
        Get
            Return _firstName
        End Get

        Set(ByVal value As String)
            _firstName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return _lastName
        End Get

        Set(ByVal value As String)
            _lastName = value
        End Set
    End Property

    Public Property Address() As String
        Get
            Return _address
        End Get

        Set(ByVal value As String)
            _address = value
        End Set
    End Property

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal address As String)
        Me.FirstName = firstName
        Me.LastName = lastName
        Me.Address = address
    End Sub

End Class

Public Class Customers
    Inherits ObservableCollection(Of Customer)

    Public Sub New()
        Add(New Customer("Michael", "Anderberg", "12 North Third Street, Apartment 45"))
        Add(New Customer("Chris", "Ashton", "34 West Fifth Street, Apartment 67"))
        Add(New Customer("Seo-yun", "Jun", "56 East Seventh Street, Apartment 89"))
        Add(New Customer("Guido", "Pica", "78 South Ninth Street, Apartment 10"))
    End Sub

End Class

Remarks

A DataTemplate object is used as the value for these properties:

You typically use a DataTemplate to specify the visual representation of your data. DataTemplate objects are particularly useful when you are binding an ItemsControl such as a ListBox to an entire collection. Without specific instructions, a ListBox displays the string representation of the objects in a collection. Use a DataTemplate to define the appearance of each of your data objects. The content of your DataTemplate becomes the visual structure of your data objects.

You typically use data binding in a DataTemplate. For example, suppose that a ListBox is bound to a collection of Customer objects and has the ItemTemplate property set to a DataTemplate. When the ListBox is created, a ListBoxItem is created for each Customer in the collection, and the DataContext of the ListBoxItem is set to the appropriate customer. In other words, the DataContext of the first ListBoxItem is set to the first customer, the DataContext of the second ListBoxItem is set to the second customer, and so on. You can bind elements in the DataTemplate to show property values that come from each of the Customer objects.

You can also use a DataTemplate to share UIElement objects across multiple ContentControl objects. For example, suppose you need multiple buttons on your application to have the same graphic. You can create a DataTemplate that contains the graphic and use it as the ContentTemplate for the buttons. A data template for ContentTemplate can also use data binding. But in this case the data context is the same as the element where the template's applied. Usually this is one data object, and there's no concept of items.

You can place a DataTemplate as the direct child of an ItemTemplate property element in XAML. This is know as an inline template and you'd do this if you had no need to use that same data template for other areas of your UI. You can also define a DataTemplate as a resource and then reference the resource as the value of the ItemTemplate property. Once it's a resource, you can use the same template for multiple UI elements that need a data template. If you factor the data template into Application.Resources, you can even share the same template for different pages of your UI.

The XAML usage for contents of a data template is not exposed as a settable code property. It is special behavior built into the XAML processing for a DataTemplate.

For advanced data binding scenarios, you might want to have properties of the data determine which template should produce their UI representations. For this scenario, you can use a DataTemplateSelector and set properties such as ItemTemplateSelector to assign it to a data view. A DataTemplateSelector is a logic class you write yourself, which has a method that returns exactly one DataTemplate to the binding engine based on your own logic interacting with your data. For more info, see Data binding in depth.

XAML attached properties

DataTemplate is the host service class for a XAML attached property.

In order to support XAML processor access to the attached properties, and also to expose equivalent get and set operations to code, each XAML attached property has a pair of Get and Set accessor methods. Another way to get or set the value in code is to use the dependency property system, calling either GetValue or SetValue and passing the identifier field as the dependency property identifier.

Attached property Description
ExtensionInstance Gets or sets an extension instance that defines helper methods for phased rendering of a data template.

Version history

Windows version SDK version Value added
1809 17763 GetElement
1809 17763 RecycleElement

Constructors

DataTemplate()

Initializes a new instance of the DataTemplate class.

Properties

Dispatcher

Gets the CoreDispatcher that this object is associated with. The CoreDispatcher represents a facility that can access the DependencyObject on the UI thread even if the code is initiated by a non-UI thread.

(Inherited from DependencyObject)
ExtensionInstanceProperty

Identifies the ExtensionInstance XAML attached property.

Attached Properties

ExtensionInstance

Gets or sets an extension instance that defines helper methods for phased rendering of a data template.

Methods

ClearValue(DependencyProperty)

Clears the local value of a dependency property.

(Inherited from DependencyObject)
GetAnimationBaseValue(DependencyProperty)

Returns any base value established for a dependency property, which would apply in cases where an animation is not active.

(Inherited from DependencyObject)
GetElement(ElementFactoryGetArgs)

Creates or retrieves an existing instance of the UIElement object declared in the DataTemplate.

GetExtensionInstance(FrameworkElement)

Gets the value of the DataTemplate.ExtensionInstance XAML attached property for the target element.

GetValue(DependencyProperty)

Returns the current effective value of a dependency property from a DependencyObject.

(Inherited from DependencyObject)
LoadContent()

Creates the UIElement objects in the DataTemplate.

ReadLocalValue(DependencyProperty)

Returns the local value of a dependency property, if a local value is set.

(Inherited from DependencyObject)
RecycleElement(ElementFactoryRecycleArgs)

Recycles a UIElement that was previously retrieved using GetElement.

RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback)

Registers a notification function for listening to changes to a specific DependencyProperty on this DependencyObject instance.

(Inherited from DependencyObject)
SetExtensionInstance(FrameworkElement, IDataTemplateExtension)

Sets the value of the DataTemplate.ExtensionInstance XAML attached property for a target element.

SetValue(DependencyProperty, Object)

Sets the local value of a dependency property on a DependencyObject.

(Inherited from DependencyObject)
UnregisterPropertyChangedCallback(DependencyProperty, Int64)

Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback.

(Inherited from DependencyObject)

Applies to

See also