2012-10-22 56 views
0

我已经现在如何解决我的问题,但我需要解释它为什么这样工作。我创建了一个测试附加属性,该属性设置TextBlock控件的Text属性。因为我需要在我的附加属性有更多的参数,我做出接受的一般性质(IGeneralAttProp)的财产,这样我就可以这样使用它:绑定到FrameworkElement属性内的附属属性

<TextBlock> 
     <local:AttProp.Setter> 
      <local:AttPropertyImpl TTD="{Binding TextToDisplay}" /> 
     </local:AttProp.Setter> 
    </TextBlock> 

这里有Setter附加属性的实现和IGeneralAttProp接口:

public class AttProp { 
    #region Setter dependancy property 
    // Using a DependencyProperty as the backing store for Setter. 
    public static readonly DependencyProperty SetterProperty = 
     DependencyProperty.RegisterAttached("Setter", 
      typeof(IGeneralAttProp), 
      typeof(AttProp), 
      new PropertyMetadata((s, e) => { 
       IGeneralAttProp gap = e.NewValue as IGeneralAttProp; 
       if (gap != null) { 
        gap.Initialize(s); 
       } 
      })); 

    public static IGeneralAttProp GetSetter(DependencyObject element) { 
     return (IGeneralAttProp)element.GetValue(SetterProperty); 
    } 

    public static void SetSetter(DependencyObject element, IGeneralAttProp value) { 
     element.SetValue(SetterProperty, value); 
    } 
    #endregion 
} 

public interface IGeneralAttProp { 
    void Initialize(DependencyObject host); 
} 

AttPropertyImpl类的实现:

class AttPropertyImpl: Freezable, IGeneralAttProp { 
    #region IGeneralAttProp Members 
    TextBlock _host; 
    public void Initialize(DependencyObject host) { 
     _host = host as TextBlock; 
     if (_host != null) { 
      _host.SetBinding(TextBlock.TextProperty, new Binding("TTD") { Source = this, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); 
     } 
    } 
    #endregion 

    protected override Freezable CreateInstanceCore() { 
     return new AttPropertyImpl(); 
    } 


    #region TTD dependancy property 
    // Using a DependencyProperty as the backing store for TTD. 
    public static readonly DependencyProperty TTDProperty = 
     DependencyProperty.Register("TTD", typeof(string), typeof(AttPropertyImpl)); 

    public string TTD { 
     get { return (string)GetValue(TTDProperty); } 
     set { SetValue(TTDProperty, value); } 
    } 
    #endregion 
} 

一切工作正常,如果AttPropertyImpl继承Freezable。如果它只是一个DependencyObject比它无法绑定消息:

无法找到控制目标元素的FrameworkElement或FrameworkContentElement。 BindingExpression:路径= TextToDisplay;的DataItem = NULL;目标元素是'AttPropertyImpl'(HashCode = 15874253);目标属性是'TTD'(类型'String')

当它是FrameworkElement时,绑定中没有错误,但值没有绑定。

问题是:为什么AttPropertyImpl必须继承Freezable才能正常工作。

回答

0

问题是AttPropertyImpl不在元素树中,看看这个post,它解释了在这种情况下Freezable对象的作用。