Bağımlılık Özellikleri Genel Bakış
Windows Presentation Foundation (WPF) provides a set of services that can be used to extend the functionality of a common language runtime (CLR) property. Collectively, these services are typically referred to as the WPF property system. Tarafından desteklenen bir özellik WPF özellik sistemi olarak bilinen bir bağımlılık özelliği. Bu genel bakışı açıklar WPF özelliği sistem ve yeteneklerini bir bağımlılık özelliği. Bu mevcut kullanımını içerir Bağımlılık Özellikleri xaml ve kod. This overview also introduces specialized aspects of dependency properties, such as dependency property metadata, and how to create your own dependency property in a custom class.
Bu konu aşağıdaki bölümleri içerir.
- Prerequisites
- Dependency Properties and CLR Properties
- Dependency Properties Back CLR Properties
- Setting Property Values
- Property Functionality Provided by a Dependency Property
- Dependency Property Value Precedence
- Learning More About Dependency Properties
- İlgili Konular
Prerequisites
This topic assumes that you have some basic knowledge of the CLR and object-oriented programming. In order to follow the examples in this topic, you should also understand XAML and know how to write WPF applications. For more information, see İzlenecek Yol: WPF Kullanmaya Başlarken.
Dependency Properties and CLR Properties
In WPF, properties are typically exposed as common language runtime (CLR) properties. At a basic level, you could interact with these properties directly and never know that they are implemented as a dependency property. However, you should become familiar with some or all of the features of the WPF property system, so that you can take advantage of these features.
The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs. These other inputs might include system properties such as themes and user preference, just-in-time property determination mechanisms such as data binding and animations/storyboards, multiple-use templates such as resources and styles, or values known through parent-child relationships with other elements in the element tree. In addition, a dependency property can be implemented to provide self-contained validation, default values, callbacks that monitor changes to other properties, and a system that can coerce property values based on potentially runtime information. Derived classes can also change some specific characteristics of an existing property by overriding dependency property metadata, rather than overriding the actual implementation of existing properties or creating new properties.
In the SDK reference, you can identify which property is a dependency property by the presence of the Dependency Property Information section on the managed reference page for that property. The Dependency Property Information section includes a link to the DependencyProperty identifier field for that dependency property, and also includes a list of the metadata options that are set for that property, per-class override information, and other details.
Dependency Properties Back CLR Properties
Dependency properties and the WPF property system extend property functionality by providing a type that backs a property, as an alternative implementation to the standard pattern of backing the property with a private field. The name of this type is DependencyProperty. The other important type that defines the WPF property system is DependencyObject. DependencyObject defines the base class that can register and own a dependency property.
Following is a summation of the terminology that is used in this software development kit (SDK) documentation when discussing dependency properties:
Bağımlılık özelliği: Tarafından desteklenen bir özellik bir DependencyProperty.
Dependency property identifier: A DependencyProperty kaydederken bir dönüş değeri elde edilen örnek bir bağımlılık özelliğive statik bir sınıfın üyesi olarak saklanır. Bu tanımlayıcı bir parametre olarak çoğu için kullanılan APIs ile etkileşimine WPF özelliği sistem.
CLR "wrapper": The actual get and set implementations for the property. These implementations incorporate the dependency property identifier by using it in the GetValue and SetValue calls, thus providing the backing for the property using the WPF property system.
The following example defines the IsSpinning dependency property, and shows the relationship of the DependencyProperty identifier to the property that it backs.
Public Shared ReadOnly IsSpinningProperty As DependencyProperty =
DependencyProperty.Register("IsSpinning",
GetType(Boolean),
GetType(MyCode))
Public Property IsSpinning() As Boolean
Get
Return CBool(GetValue(IsSpinningProperty))
End Get
Set(ByVal value As Boolean)
SetValue(IsSpinningProperty, value)
End Set
End Property
public static readonly DependencyProperty IsSpinningProperty =
DependencyProperty.Register(
"IsSpinning", typeof(Boolean),
...
);
public bool IsSpinning
{
get { return (bool)GetValue(IsSpinningProperty); }
set { SetValue(IsSpinningProperty, value); }
}
The naming convention of the property and its backing DependencyProperty field is important. The name of the field is always the name of the property, with the suffix Property appended. For more information about this convention and the reasons for it, see Özel Bağımlılık Özellikleri.
Setting Property Values
Kod veya xaml özelliklerini ayarlayabilirsiniz.
Setting Property Values in XAML
Aşağıdaki xaml örnek bir düğme arka plan rengini kırmızı olarak belirler. xaml özniteliğinin basit dize değeri olduğu türü-dönüştürülmesi wpf xaml çözümleyici tarafından servis talebi Bu örnekte gösterilmektedir bir WPF türü (bir Color, yoluyla bir SolidColorBrush) oluşturulan kodu.
<Button Background="Red" Content="Button!"/>
xaml özelliklerini ayarlamak için sözdizimi çeşitli destekler. Which syntax to use for a particular property will depend on the value type that a property uses, as well as other factors such as the presence of a type converter. Özellik ayarı için xaml sözdizimi hakkında daha fazla bilgi için bkz: XAML'e Genel Bakış (WPF) ve Ayrıntılı XAML Sözdizimi.
Özniteliği olmayan sözdizimine örnek, aşağıdaki xaml örnek başka bir düğme arka planını gösterir. This time rather than setting a simple solid color, the background is set to an image, with an element representing that image and the source of that image specified as an attribute of the nested element. This is an example of property element syntax.
<Button Content="Button!">
<Button.Background>
<ImageBrush ImageSource="wavy.jpg"/>
</Button.Background>
</Button>
Setting Properties in Code
Ayarlama bağımlılık özelliği kod değerleri ise genellikle yalnızca bir çağrı tarafından sergilenen kümesi uygulama CLR "kapsayıcı".
Dim myButton As New Button()
myButton.Width = 200.0
Button myButton = new Button();
myButton.Width = 200.0;
Getting a property value is also essentially a call to the get "wrapper" implementation:
Dim whatWidth As Double
whatWidth = myButton.Width
double whatWidth;
whatWidth = myButton.Width;
You can also call the property system APIs GetValue and SetValue directly. This is not typically necessary if you are using existing properties (the wrappers are more convenient, and provide better exposure of the property for developer tools), but calling the APIs directly is appropriate for certain scenarios.
Özellikler ayrıca xaml ayarlayın ve sonra devamındaki kodu, kod arkada aracılığıyla erişilen. For details, see Arka Plan Kodu ve WPF içindeki XAML.
Property Functionality Provided by a Dependency Property
A dependency property provides functionality that extends the functionality of a property as opposed to a property that is backed by a field. Often, each such functionality represents or supports a specific feature of the overall WPF set of features:
Resources
Data binding
Styles
Animations
Metadata overrides
Property value inheritance
WPF Designer integration
Resources
A dependency property value can be set by referencing a resource. Kaynakları tipik olarak belirtilen Resources özellik değeri sayfa kök öğesinin ya da (Bu konumları, en uygun kaynak erişimi etkinleştir) uygulamasının. The following example shows how to define a SolidColorBrush resource.
<DockPanel.Resources>
<SolidColorBrush x:Key="MyBrush" Color="Gold"/>
</DockPanel.Resources>
Once the resource is defined, you can reference the resource and use it to provide a property value:
<Button Background="{DynamicResource MyBrush}" Content="I am gold" />
Bu belirli kaynağa olarak başvurulan bir DynamicResource Biçimlendirme Uzantısı (wpf xaml statik veya dinamik kaynağın başvuru kullanabilirsiniz). To use a dynamic resource reference, you must be setting to a dependency property, so it is specifically the dynamic resource reference usage that is enabled by the WPF property system. For more information, see Kaynaklara Genel Bakış.
Not |
---|
Resources are treated as a local value, which means that if you set another local value, you will eliminate the resource reference.For more information, see Bağımlılık Özelliği Değer Önceliği. |
Data Binding
A dependency property can reference a value through data binding. xaml belirli biçimlendirme uzantısı sözdizimini üzerinden veri veya Binding nesne kodu. With data binding, the final property value determination is deferred until run time, at which time the value is obtained from a data source.
Aşağıdaki örnek ayarlar Content özelliği için bir Buttonkullanarak bağlama bildirilen xaml. The binding uses an inherited data context and an XmlDataProvider data source (not shown). The binding itself specifies the desired source property by XPath within the data source.
<Button Content="{Binding XPath=Team/@TeamName}"/>
Not |
---|
Bindings are treated as a local value, which means that if you set another local value, you will eliminate the binding.For details, see Bağımlılık Özelliği Değer Önceliği. |
Dependency properties, or the DependencyObject class, do not natively support INotifyPropertyChanged for purposes of producing notifications of changes in DependencyObject source property value for data binding operations. For more information on how to create properties for use in data binding that can report changes to a data binding target, see Veri Bağlama Genel Bakış.
Styles
Styles and templates are two of the chief motivating scenarios for using dependency properties. Styles are particularly useful for setting properties that define application user interface (UI). Stilleri genellikle xaml kaynakları olarak tanımlanır. Styles interact with the property system because they typically contain "setters" for particular properties, as well as "triggers" that change a property value based on the real-time value for another property.
The following example creates a very simple style (which would be defined inside a Resources dictionary, not shown), then applies that style directly to the Style property for a Button. The setter within the style sets the Background property for a styled Button to green.
<Style x:Key="GreenButtonStyle">
<Setter Property="Control.Background" Value="Green"/>
</Style>
<Button Style="{StaticResource GreenButtonStyle}">I am green!</Button>
For more information, see Stillendirme ve Şablon Oluşturma.
Animations
Dependency properties can be animated. When an animation is applied and is running, the animated value operates at a higher precedence than any value (such as a local value) that the property otherwise has.
The following example animates the Background on a Button property (technically, the Background is animated by using property element syntax to specify a blank SolidColorBrush as the Background, then the Color property of that SolidColorBrush is the property that is directly animated).
<Button>I am animated
<Button.Background>
<SolidColorBrush x:Name="AnimBrush"/>
</Button.Background>
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Loaded">
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetName="AnimBrush"
Storyboard.TargetProperty="(SolidColorBrush.Color)"
From="Red" To="Green" Duration="0:0:5"
AutoReverse="True" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
For more information on animating properties, see Animasyona Genel bakış and Film Şeritlerine Genel Bakış.
Metadata Overrides
You can change certain behaviors of a dependency property by overriding the metadata for that property when you derive from the class that originally registers the dependency property. Overriding metadata relies on the DependencyProperty identifier. Overriding metadata does not require re-implementing the property. The metadata change is handled natively by the property system; each class potentially holds individual metadata for all properties that are inherited from base classes, on a per-type basis.
The following example overrides metadata for a dependency property DefaultStyleKey. Overriding this particular dependency property metadata is part of an implementation pattern that creates controls that can use default styles from themes.
Public Class SpinnerControl
Inherits ItemsControl
Shared Sub New()
DefaultStyleKeyProperty.OverrideMetadata(GetType(SpinnerControl), New FrameworkPropertyMetadata(GetType(SpinnerControl)))
End Sub
End Class
public class SpinnerControl : ItemsControl
{
static SpinnerControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(SpinnerControl),
new FrameworkPropertyMetadata(typeof(SpinnerControl))
);
}
}
For more information about overriding or obtaining property metadata, see Bağımlılık Özelliği Meta Verisi.
Property Value Inheritance
Bir öğenin üst Nesne Ağacı'ndaki bir bağımlılık özelliğinin değeri devralabilir.
Not |
---|
Property value inheritance behavior is not globally enabled for all dependency properties, because the calculation time for inheritance does have some performance impact.Property value inheritance is typically only enabled for properties where a particular scenario suggests that property value inheritance is appropriate.Bağımlılık özelliği bakarak devralıp almayacağını belirlemek Bağımlılık özelliği bilgilerini , bağımlılık özelliği sdk Başvurusu bölümüne. |
The following example shows a binding, and sets the DataContext property that specifies the source of the binding, which was not shown in the earlier binding example. Any subsequent bindings in child objects do not need to specify the source, they can use the inherited value from DataContext in the parent StackPanel object. (Alternatively, a child object could instead choose to directly specify its own DataContext or a Source in the Binding, and to deliberately not use the inherited value for data context of its bindings.)
<StackPanel Canvas.Top="50" DataContext="{Binding Source={StaticResource XmlTeamsSource}}">
<Button Content="{Binding XPath=Team/@TeamName}"/>
</StackPanel>
For more information, see Özellik Değeri Kalıtımı.
WPF Designer Integration
A custom control with properties that are implemented as dependency properties will receive appropriate Visual Studio için WPF Tasarımcısı support. One example is the ability to edit direct and attached dependency properties with the Properties window. For more information, see Denetim Yazımına Genel Bakış.
Dependency Property Value Precedence
When you get the value of a dependency property, you are potentially obtaining a value that was set on that property through any one of the other property-based inputs that participate in the WPF property system. Dependency property value precedence exists so that a variety of scenarios for how properties obtain their values can interact in a predictable way.
Consider the following example. The example includes a style that applies to all buttons and their Background properties, but then also specifies one button with a locally set Background value.
Not |
---|
The SDK documentation uses the terms "local value" or "locally set value" occasionally when discussing dependency properties.Yerel olarak belirlenen doğrudan bir nesne örneği kodu veya bir öğede xaml nitelik olarak ayarlanmış bir özellik değeri değerdir. |
İlk düğme için prensipte özelliği iki kez ayarlandı ancak tek bir değer uygulanır: the value with the highest precedence. A locally set value has the highest precedence (except for a running animation, but no animation applies in this example) and thus the locally set value is used instead of the style setter value for the background on the first button. The second button has no local value (and no other value with higher precedence than a style setter) and thus the background in that button comes from the style setter.
<StackPanel>
<StackPanel.Resources>
<Style x:Key="{x:Type Button}" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Red"/>
</Style>
</StackPanel.Resources>
<Button Background="Green">I am NOT red!</Button>
<Button>I am styled red</Button>
</StackPanel>
Why Does Dependency Property Precedence Exist?
Typically, you would not want styles to always apply and to obscure even a locally set value of an individual element (otherwise, it would be very difficult to use either styles or elements in general). Therefore, the values that come from styles operate at a lower precedent than a locally set value. For a more thorough listing of dependency properties and where a dependency property effective value might come from, see Bağımlılık Özelliği Değer Önceliği.
Not |
---|
There are a number of properties defined on WPF elements that are not dependency properties.By and large, properties were implemented as dependency properties only when there were needs to support at least one of the scenarios enabled by the property system: data binding, styling, animation, default value support, inheritance, attached properties, or invalidation. |
Learning More About Dependency Properties
Bir bağlı özellik özel bir sözdizimi xaml destekleyen özelliği türüdür. An attached property often does not have a 1:1 correspondence with a common language runtime (CLR) property, and is not necessarily a dependency property. The typical purpose of a attached property is to allow child elements to report property values to a parent element, even if the parent element and child element do not both possess that property as part of the class members listings. One primary scenario is to enable child elements to inform the parent how they should be presented in UI; for an example, see Dock or Left. For details, see Ekli Özelliklere Genel Bakış.
Component developers or application developers may wish to create their own dependency property, in order to enable capabilities such as data binding or styles support, or for invalidation and value coercion support. For details, see Özel Bağımlılık Özellikleri.
Dependency properties should generally be considered to be public properties, accessible or at least discoverable by any caller that has access to an instance. For more information, see Bağımlılık Özelliği Güvenlik.