PropertyDescriptor and DependencyPropertyDescriptor

from MSDN:

 

PropertyDescriptor provides an abstraction of a property on a class

 

DepednencyPropertyDescriptor provides an extension to PropertyDescriptor that accounts for the additional property characteristics of a dependency property.

 

Suppose, there is a dependency property that is called "PersistenceConfigurationProperty", and it is declared in a WindowPersistence class. 

 

 

 

 

    public static readonly DependencyProperty PersistenceConfigurationProperty = DependencyProperty.RegisterAttached(
        "PersistenceConfiguration",
        typeof(ApplicationPersistence),
        typeof(WindowPersistence),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits, OnSetPersistenceConfigurationCallback));

 

 

and in one of the extension class that is called PersistableResourceExtension, with the help of DependencyPropertyDescriptor, we can remove the Value Changed Handler.

 

 

 DependencyPropertyDescriptor persistenceConfigurationProperty = DependencyPropertyDescriptor.FromProperty(
            WindowPersistence.PersistenceConfigurationProperty, m_targetObject.GetType());
          persistenceConfigurationProperty.RemoveValueChanged(m_targetObject, PersistenceConfigurationPropertyChanged);
 

There is another examples that use reflection and other things to change the Bindings on a DependencyProperty

 

 

 

      if (profileWarningWindow != null)
      {
        DependencyPropertyDescriptor persistenceConfiguration = DependencyPropertyDescriptor.FromProperty(WindowPersistence.PersistenceConfigurationProperty, typeof(AdminShellWindow));
        if (persistenceConfiguration != null)
        {
          Type windowPersistenceType = typeof(WindowPersistence);
          if (windowPersistenceType != null)
          {
            var method = windowPersistenceType.GetMethod("OnSetPersistenceConfigurationCallback", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);

            if (method != null)
            {
              var handler = (PropertyChangedCallback)Delegate.CreateDelegate(typeof(PropertyChangedCallback), method);
              persistenceConfiguration.RemoveValueChanged(null, handler);
            }
          }          
        }
 

 

 

The code above does not necessary means a workable code, there are something that prevent it working (either compile time or runtime);

 

 

persistenceConfiguration.RemoveValueChanged(null, handler)

 

 

the required type for the second parameter of RemoveValueChanged is EventHandler.

 

 

While you cannot convert the PropertyChangedCallback to EventHandler.

你可能感兴趣的:(WPF)