Compartilhar via


Como: Implement a Dependency Property

Este exemplo mostra como fazer uma common language runtime (CLR) propriedade com um DependencyProperty campo, definindo, portanto, um propriedade de dependência. Quando você definir suas próprias propriedades e deseja que eles suportam muitos aspectos do Windows Presentation Foundation (WPF) a funcionalidade, inclusive estilos, ligação de dados, herança, animação e valores padrão, você deve implementá-los como um propriedade de dependência.

Exemplo

The following example first registers a dependency property by calling the Register method. The name of the identifier field that you use to store the name and characteristics of the dependency property must be the Name you chose for the dependency property as part of the Register call, appended by the literal string Property. For instance, if you register a dependency property with a Name of Location, then the identifier field that you define for the dependency property must be named LocationProperty.

In this example, the name of the dependency property and its CLR accessor is State; the identifier field is StateProperty; the type of the property is Boolean; and the type that registers the dependency property is MyStateControl.

If you fail to follow this naming pattern, designers might not report your property correctly, and certain aspects of property system style application might not behave as expected.

You can also specify default metadata for a dependency property. This example registers the default value of the State dependency property to be false.

  Public Class MyStateControl
      Inherits ButtonBase
    Public Sub New()
        MyBase.New()
    End Sub
    Public Property State() As Boolean
      Get
          Return CType(Me.GetValue(StateProperty), Boolean)
      End Get
      Set(ByVal value As Boolean)
          Me.SetValue(StateProperty, value)
      End Set
    End Property
    Public Shared ReadOnly StateProperty As DependencyProperty = DependencyProperty.Register("State", GetType(Boolean), GetType(MyStateControl),New PropertyMetadata(False))
  End Class
public class MyStateControl : ButtonBase
{
  public MyStateControl() : base() { }
  public Boolean State
  {
    get { return (Boolean)this.GetValue(StateProperty); }
    set { this.SetValue(StateProperty, value); } 
  }
  public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
    "State", typeof(Boolean), typeof(MyStateControl),new PropertyMetadata(false));
}

For more information about how and why to implement a dependency property, as opposed to just backing a CLR property with a private field, see Visão geral sobre propriedades de dependência.

Consulte também

Conceitos

Visão geral sobre propriedades de dependência

Outros recursos

Tópicos de Como Fazer sobre Propriedades