C# 使用附加属性时的无限递归
我需要将C# 使用附加属性时的无限递归,c#,.net,wpf,dependency-properties,dynamicresource,C#,.net,Wpf,Dependency Properties,Dynamicresource,我需要将ContentPresenter的Content属性设置为DynamicResource,该键在运行时已知DynamicSource的键不是依赖项属性,因此我无法在其中插入绑定,这就是为什么我创建了一个附加属性,作为内容的代理: public static class ContentPresenterHelper { private static void ContentResourceKeyChanged(DependencyObject d, DependencyPrope
ContentPresenter
的Content
属性设置为DynamicResource
,该键在运行时已知DynamicSource
的键
不是依赖项属性,因此我无法在其中插入绑定,这就是为什么我创建了一个附加属性,作为内容的代理:
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}" />
为什么会这样?如何解决此问题?在处理ContentPresenter
时,请始终记住ContentPresenter.Content
是一个非常特殊的属性:它会影响DataContext
。与数据绑定相结合,这可能会产生各种奇怪的效果。一般来说,通过DataContext
绑定ContentPresenter.Content
是不可靠的,应该避免。尝试使用ContentControl
,因为它不会以这种方式将其DataContext
连接到Content
。另外,我会编写一个转换器来按键查找动态资源,并使用它直接绑定内容,而不是附加属性,但这是一个品味问题。转换器的唯一问题是,它不能立即访问资源。在实例化转换器时,我必须手动附加ResourceDictionary
,不是吗?或者可能有更聪明的方法让转换器访问资源?这取决于资源的作用域。如果目标资源位于应用程序范围内,则无需访问本地上下文即可通过。但是,通过从MarkupExtension
派生,可以创建可以访问本地上下文的转换器。不过,使用模板会变得很棘手。无论如何,转换器与附属财产是一个品味问题;用ContentControl
交换ContentPresenter
彻底解决了我的问题;谢谢您的帮助,先生:)
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
...