WPF: Dependency Properties & Resources

泄露秘密 提交于 2019-12-12 22:21:11

问题


I found this on MSDN:

A dependency property value can be set by referencing a resource. Resources are typically specified as the Resources property value of a page root element, or of the application (these locations enable the most convenient access to the resource). The following example shows how to define a SolidColorBrush resource.

XAML:

<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" />

This particular resource is referenced as a DynamicResource Markup Extension . 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.

My questions are:

  1. StaticResource is not considered Dependency Property? If yes why?
  2. Does not belongs to WPF Property System?

Also can you give me an example how to implement default value using Dependency Property?


回答1:


DynamicResource is used for setting only dependency property values.

By contrast StaticResource can be used pratically everywhere. You can use it to set a dependency property value but not only. For example, you can also define an element as resource as use it inside a panel by StaticResource, such as in the code

<Window>
   <Window.Resources>
       <Button Content="btnStaticResource" x:Key="myBtn" />
   </Window.Resources>

   <Grid> 
      <StaticResource ResourceKey="myBtn" /> 
   </Grid>
</Window>

Concerning your question 1, a resource is not a dependency property, irrespective if you refer to it using StaticResource or DynamicResource markup extension.

A resource in WPF can be about anything, a .NET object, a font, an image, a color, a string etc. The concept of resource is not related to the concept of dependency property.

A dependency property is a new type of property introduced by WPF. A dependency property value depends on multiple sources according to a fixed hierarchie (for details msdn).

Concerning your question 2, yes, the concept of StaticResource is part of the WPF resource system.

Finally, for defining the default value of a dependency property see the following code:

public static readonly DependencyProperty AlphaProperty = DependencyProperty.Register   ("Alpha", typeof(int), typeof(MyButton), new FrameworkPropertyMetadata(255, FrameworkPropertyMetadataOptions.AffectsRender));

Here is defined a dependency property named Alpha, of type int and with default value 255.

I hope this helps



来源:https://stackoverflow.com/questions/12988797/wpf-dependency-properties-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!