我已經現在如何解決我的問題,但我需要解釋它爲什麼這樣工作。我創建了一個測試附加屬性,該屬性設置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
才能正常工作。