绑定到附加属性中的框架元素属性



我现在已经如何解决我的问题,但是我需要解释为什么它这样工作。我已经创建了一个附加的属性,该属性设置了TextBlock控件的Text属性。由于我需要在附件属性中拥有更多参数,因此我将属性接受了一般属性(IGeneralAttProp),因此我可以这样使用:

    <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
}

如果AttPropertyImplFreezable继承,则一切正常。如果仅是DependencyObject,则无法与消息绑定:

无法找到目标元素的框架框架或Frameworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkworkwork。bindingExpression:path = textTodIsplay;dataitem = null;目标元素为" attpropertyimpl"(哈希尺= 15874253);目标属性为" ttd"(键入'string')

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

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

问题是 AttPropertyImpl不在元素树中,看这篇文章,它解释了在这种情况下冻结对象的角色。

最新更新