开发者

Why is an attached property of type BindingExpression not evaluated when placed within a DataTemplate?

I have defined an attached property for Selector of type BindingExpression in order to catch a binding so I can clone it onto multiple properties. The attached property works fine when the Selector is defined directly in XAML. However when the Selector is defined inside a DataTemplate, the property changed handler never gets fired.

Attached Property

public static readonly DependencyProperty EnumBindingProperty = DependencyProperty.RegisterAttached(
    "EnumBinding", typeof(BindingExpression), typeof(SelectorHelper),
    new开发者_如何学Go PropertyMetadata(null, OnEnumBindingChanged));

Usage (valid)

<ComboBox AttachedProperties:SelectorHelper.EnumBinding="{Binding Phase}" />

Usage (invalid)

<DataTemplate>
    <ComboBox AttachedProperties:SelectorHelper.EnumBinding="{Binding Phase}" />
</DataTemplate>

It seems like it is a timing issue, because I've found that if I use Snoop to evaluate the property it automatically refreshes and begins to work.

Any help or explanation would be greatly appreciated. :)


It looks like the evaluation of the binding is just being delayed as long as possible since the expression is just being stored as an expression and not evaluated. You can force the evaluation by changing the attached property type to object.

public static readonly DependencyProperty EnumBindingProperty = DependencyProperty.RegisterAttached(
    "EnumBinding", typeof(object), typeof(SelectorHelper),
    new PropertyMetadata(null, OnEnumBindingChanged));

This will cause the binding to evaluate as soon as possible. You can then extract the BindingExpression from the property when it's set and use that instead of the directly set BindingExpression value that's there now.

BindingOperations.GetBindingExpression(dObj, EnumBindingProperty)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜