Compartilhar via


Sintaxe de um PropertyPath XAML

The PropertyPath object supports a complex inline XAML syntax for setting various properties that take the PropertyPath type as their value. This topic documents the PropertyPath syntax as applied to binding and animation syntaxes.

Este tópico contém as seguintes seções.

  • Where PropertyPath Is Used
  • PropertyPath for Objects in Data Binding
  • PropertyPath for Animation Targets
  • PropertyPath in Code
  • Tópicos relacionados

Where PropertyPath Is Used

PropertyPath is a common object that is used in several Windows Presentation Foundation (WPF) features. Despite using the common PropertyPath to convey property path information, the usages for each feature area where PropertyPath is used as a type vary. Therefore, it is more practical to document the syntaxes on a per-feature basis.

Primarily, WPF uses PropertyPath to describe object-model paths for traversing the properties of an object data source, and to describe the target path for targeted animations.

Some style and template properties such as Setter.Property take a qualified property name that superficially resembles a PropertyPath. Mas isso não é um verdadeiro PropertyPath; em vez disso é um qualificado owner.property o uso do formato é ativado pelo WPF em seqüência XAML o processador em combinação com o conversor de tipo de DependencyProperty.

PropertyPath for Objects in Data Binding

Data binding is a WPF feature whereby you can bind to the target value of any dependency property. However, the source of such a data binding need not be a dependency property; it can be any property type that is recognized by the applicable data provider. Property paths are particularly used for the ObjectDataProvider, which is used for obtaining binding sources from common language runtime (CLR) objects and their properties.

Note that data binding to XML does not use PropertyPath, because it does not use Path in the Binding. Em vez disso, use XPath e especifique a sintaxe do XPath válida para o XML Document Object Model (DOM) de dados. XPathtambém é especificado como uma seqüência de caracteres, mas não está documentada aqui; see Como: Bind to XML Data Using an XMLDataProvider and XPath Queries.

A key to understanding property paths in data binding is that you can target the binding to an individual property value, or you can instead bind to target properties that take lists or collections. Se você estiver vinculando a coleções, por exemplo, vinculação de um ListBox que se expandirá dependendo de quantos itens de dados estão na coleção, e seu caminho de propriedade deve fazer referência a objeto da coleção, itens de coleção individual. O mecanismo de ligação de dados corresponderá a coleção usada como a fonte de dados para o tipo de destino de vinculação automaticamente, resultando em comportamento como preencher um ListBox com uma matriz de itens.

Single Property on the Immediate Object as Data Context

<Binding Path="propertyName" .../>

propertyName must resolve to be the name of a property that is in the current DataContext for a Path usage. If your binding updates the source, that property must be read/write and the source object must be mutable.

Single Indexer on the Immediate Object as Data Context

<Binding Path="[key]" .../>

key must be either the typed index to a dictionary or hash table, or the integer index of an array. Also, the value of the key must be a type that is directly bindable to the property where it is applied. For instance, a hash table that contains string keys and string values can be used this way to bind to Text for a TextBox. Or, if the key points to a collection or subindex, you could use this syntax to bind to a target collection property. Caso contrário, você precisa referenciar uma propriedade específica, por meio de uma sintaxe como <Binding Path="[key].propertyName" .../>.

You can specify the type of the index if necessary. For details on this aspect of an indexed property path, see Binding.Path.

Multiple Property (Indirect Property Targeting)

<Binding Path="propertyName.propertyName2" .../>

propertyName must resolve to be the name of a property that is the current DataContext. The path properties propertyName and propertyName2 can be any properties that exist in a relationship, where propertyName2 is a property that exists on the type that is the value of propertyName.

Única propriedade anexada ou caso contrário qualificados de tipo

<object property="(ownerType.propertyName)" .../>

The parentheses indicate that this property in a PropertyPath should be constructed using a partial qualification. Ele pode usar um namespace XML para localizar o tipo com um mapeamento apropriado. The ownerType searches types that a XAML processor has access to, through the XmlnsDefinitionAttribute declarations in each assembly. A maioria dos aplicativos tem o namespace XML padrão mapeado para o https://schemas.microsoft.com/winfx/2006/xaml/presentation namespace, portanto, um prefixo geralmente é necessário somente para tipos personalizados ou tipos contrário fora do espaço para nome. propertyNamedeve resolver o nome de uma propriedade existente na ownerType. This syntax is generally used for one of the following cases:

  • The path is specified in XAML that is in a style or template that does not have a specified Target Type. A qualified usage is generally not valid for cases other than this, because in non-style, non-template cases, the property exists on an instance, not a type.

  • The property is an attached property.

  • You are binding to a static property.

For use as storyboard target, the property specified as propertyName must be a DependencyProperty.

Source Traversal (Binding to Hierarchies of Collections)

<object Path="propertyName/propertyNameX" .../>

The / in this syntax is used to navigate within a hierarchical data source object, and multiple steps into the hierarchy with successive / characters are supported. The source traversal accounts for the current record pointer position, which is determined by synchronizing the data with the UI of its view. For details on binding with hierarchical data source objects, and the concept of current record pointer in data binding, see Como: Use the Master-Detail Pattern with Hierarchical Data or Revisão de Associação de Dados.

Observação

Superficially, this syntax resembles XPath.A true XPath expression for binding to an XML data source is not used as a Path value and should instead be used for the mutually exclusive XPath property.

Collection Views

Para fazer referência a um modo de exibição de conjunto nomeado, o nome de exibição da coleção com o caractere de prefixo (#).

Ponteiro de registro atual

Para fazer referência o ponteiro de registro atual para um modo de exibição de coleção ou um cenário de vinculação de dados de detalhes mestre, iniciar a seqüência de caracteres de caminho com uma barra invertida (/). Qualquer caminho após a barra é atravessado a partir do ponteiro de registro atual.

Multiple Indexers

<object Path="[index1,index2...]" .../>
or
<object Path="propertyName[index,index2...]" .../>

If a given object supports multiple indexers, those indexers can be specified in order, similar to an array referencing syntax. The object in question can be either the current context or the value of a property that contains a multiple index object.

By default, the indexer values are typed by using the characteristics of the underlying object. You can specify the type of the index if necessary. For details on typing the indexers, see Binding.Path.

Mixing Syntaxes

Each of the syntaxes shown above can be interspersed. For instance, the following is an example that creates a property path to the color at a particular x,y of a ColorGrid property that contains a pixel grid array of SolidColorBrush objects:

<Rectangle Fill="{Binding ColorGrid[20,30].SolidColorBrushResult}" .../>

Escapa para seqüências de caminho de propriedade

Para determinados objetos de negócios, você pode encontrar um caso onde a seqüência de caracteres de caminho propriedade requer uma seqüência de escape para analisar corretamente. A necessidade de escape deve ser rara, porque muitos desses caracteres têm problemas de nomeação de interação semelhantes em linguagens que costumam ser usadas para definir o objeto comercial.

  • Inside indexers ([ ]), the caret character (^) escapes the next character.

  • Você deve sair (usando a entidades XML) determinados caracteres especiais para a definição de linguagem XML. Use &amp; to escape the character "&". Use [] to escape the end tag ">".

  • É necessário sair (usando a barra invertida \) caracteres são especiais para o comportamento do analisador de WPF XAML para o processamento de uma extensão de marcação.

    • Barra invertida (\) é o caractere de escape.

    • O sinal de igual (=) separa o nome da propriedade do valor da propriedade.

    • Vírgula (,) separa propriedades.

    • A chave direita (}) é o fim de uma extensão de marcação.

Observação

Tecnicamente, esses escapa trabalha para um caminho de propriedade do storyboard, também, mas você normalmente está atravessando os modelos de objeto para objetos existentes do WPF e saída deve ser desnecessário.

PropertyPath for Animation Targets

The target property of an animation must be a dependency property that takes either a Freezable or a primitive type. However, the targeted property on a type and the eventual animated property can exist on different objects. For animations, a property path is used to define the connection between the named animation target object's property and the intended target animation property, by traversing object-property relationships in the property values.

General Object-Property Considerations for Animations

For more information on animation concepts in general, see Visão geral sobre Storyboards and Revisão de Animação.

The value type or the property being animated must be either a Freezable type or a primitive. The property that starts the path must resolve to be the name of a dependency property that exists on the specified TargetName type.

In order to support cloning for animating a Freezable that is already frozen, the object specified by TargetName must be a FrameworkElement or FrameworkContentElement derived class.

Single Property on the Target Object

<animation Storyboard.TargetProperty="propertyName" .../>

propertyName must resolve to be the name of a dependency property that exists on the specified TargetName type.

Indirect Property Targeting

<animation Storyboard.TargetProperty="propertyName.propertyName2" .../>

propertyName must be a property that is either a Freezable value type or a primitive, which exists on the specified TargetName type.

propertyName2 must be the name of a dependency property that exists on the object that is the value of propertyName. In other words, propertyName2 must exist as a dependency property on the type that is the propertyName PropertyType.

Indirect targeting of animations is necessary because of applied styles and templates. In order to target an animation, you need a TargetName on a target object, and that name is established by x:Name or Name. Although template and style elements also can have names, those names are only valid within the namescope of the style and template. (If templates and styles did share namescopes with application markup, names couldn't be unique. The styles and templates are literally shared between instances and would perpetuate duplicate names.) Thus, if the individual properties of an element that you might wish to animate came from a style or template, you need to start with a named element instance that is not from a style template, and then target into the style or template visual tree to arrive at the property you wish to animate.

For instance, the Background property of a Panel is a complete Brush (actually a SolidColorBrush) that came from a theme template. To animate a Brush completely, there would need to be a BrushAnimation (probably one for every Brush type) and there is no such type. To animate a Brush, you instead animate properties of a particular Brush type. You need to get from SolidColorBrush to its Color to apply a ColorAnimation there. The property path for this example would be Background.Color.

Attached Properties

<animation Storyboard.TargetProperty="(ownerType.propertyName)" .../>

The parentheses indicate that this property in a PropertyPath should be constructed using a partial qualification. Ele pode usar um namespace XML para localizar o tipo. The ownerType searches types that a XAML processor has access to, through the XmlnsDefinitionAttribute declarations in each assembly. A maioria dos aplicativos tem o namespace XML padrão mapeado para o https://schemas.microsoft.com/winfx/2006/xaml/presentation namespace, portanto, um prefixo geralmente é necessário somente para tipos personalizados ou tipos contrário fora do espaço para nome. propertyNamedeve resolver o nome de uma propriedade existente na ownerType. The property specified as propertyName must be a DependencyProperty. (All WPF attached properties are implemented as dependency properties, so this issue is only of concern for custom attached properties.)

Indexers

<animation Storyboard.TargetProperty="propertyName.propertyName2[index].propertyName3" .../>

Most dependency properties or Freezable types do not support an indexer. Therefore, the only usage for an indexer in an animation path is at an intermediate position between the property that starts the chain on the named target and the eventual animated property. In the provided syntax, that is propertyName2. For instance, an indexer usage might be necessary if the intermediate property is a collection such as TransformGroup, in a property path such as RenderTransform.Children[1].Angle.

PropertyPath in Code

Code usage for PropertyPath, including how to construct a PropertyPath, is documented in the reference topic for PropertyPath.

In general, PropertyPath is designed to use two different constructors, one for the binding usages and simplest animation usages, and one for the complex animation usages. Use the PropertyPath(Object) signature for binding usages, where the object is a string. Use the PropertyPath(Object) signature for one-step animation paths, where the object is a DependencyProperty. Use the PropertyPath(String, Object[]) signature for complex animations. This latter constructor uses a token string for the first parameter and an array of objects that fill positions in the token string to define a property path relationship.

Consulte também

Referência

PropertyPath

Conceitos

Revisão de Associação de Dados

Visão geral sobre Storyboards