我需要将 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
...
为什么会这样?我怎么解决这个问题?