1

我需要将 a 的Content属性设置ContentPresenter为 a DynamicResource,该键在运行时是已知的。DynamicResource'sKey不是依赖属性,所以我不能在那里插入绑定,这就是为什么我创建了一个附加属性,它充当 的代理Content

public static class ContentPresenterHelper {

    private static void ContentResourceKeyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {

        var element = d as ContentPresenter;
        if (element != null) {

            element.SetResourceReference(ContentPresenter.ContentProperty, e.NewValue);
        }
    }

    public static readonly DependencyProperty ContentResourceKeyProperty = DependencyProperty.RegisterAttached("ContentResourceKey",
        typeof(object),
        typeof(ContentPresenterHelper),
        new PropertyMetadata(String.Empty, ContentResourceKeyChanged));

    public static void SetContentResourceKey(ContentPresenter element, object value) {

        element.SetValue(ContentResourceKeyProperty, value);
    }

    public static object GetContentResourceKey(ContentPresenter element) {

        return element.GetValue(ContentResourceKeyProperty);
    }
}

我通过以下方式使用它:

<ContentPresenter u:ContentPresenterHelper.ContentResourceKey="{Binding SomeProp}" />

Image在将资源中的动态图像分配给' 的Source属性时,我使用了类似的方法,并且有效。

但是,在这种特殊情况下,尝试以我展示的方式解决问题会导致无限递归:

PresentationFramework.dll!System.Windows.FrameworkElement.IsLoaded.get()    Unknown
PresentationFramework.dll!MS.Internal.FrameworkObject.IsLoaded.get()    Unknown
PresentationFramework.dll!System.Windows.BroadcastEventHelper.IsParentLoaded(System.Windows.DependencyObject d) Unknown
PresentationFramework.dll!System.Windows.FrameworkElement.IsLoaded.get()    Unknown
PresentationFramework.dll!MS.Internal.FrameworkObject.IsLoaded.get()    Unknown
PresentationFramework.dll!System.Windows.BroadcastEventHelper.IsParentLoaded(System.Windows.DependencyObject d) Unknown
PresentationFramework.dll!System.Windows.FrameworkElement.IsLoaded.get()    Unknown
PresentationFramework.dll!MS.Internal.FrameworkObject.IsLoaded.get()    Unknown
...

为什么会这样?我怎么解决这个问题?

4

1 回答 1

1

玩弄 时ContentPresenter,请始终记住这ContentPresenter.Content是一个非常特殊的属性:它会影响DataContext. 结合数据绑定,这会产生各种奇怪的效果。一般来说,绑定ContentPresenter.Content通过DataContext是不可靠的,应该避免。尝试使用ContentControl,因为它不会DataContextContent这种方式连接到它。另外,我会编写一个转换器来按键查找您的动态资源,并使用它Content直接绑定,而不是附加属性,但这只是个人喜好问题。

于 2014-01-20T08:07:02.120 回答