绑定到附加属性中的FrameworkElement属性

时间:2012-10-22 09:39:48

标签: c# binding attached-properties freezable

我现在已经解决了我的问题,但我需要解释为什么它会这样运作。我创建了一个测试附加属性,用于设置Text控件的TextBlock属性。由于我需要在附加属性中包含更多参数,因此我使该属性接受了一般属性(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
}

如果AttPropertyImpl继承自Freezable,那么一切正常。如果它只是DependencyObject而不是与消息绑定:

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

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

问题:为什么AttPropertyImpl必须继承Freezable才能正常使用。

1 个答案:

答案 0 :(得分:0)

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

相关问题