.NET中Ambient属性的用途是什么?

3
有人能否解释一下.NET中的环境属性(Ambient Attribute)?
2个回答

3

它用于解决像
<Setter Property="P" Value="V" />
这样的问题。在将V转换为正确类型的值之前,您必须了解P(实际上是P的类型)。 您可以使用[Ambient]标记“Property”属性,并且1.加载程序将首先处理“Property”,2.允许“Value”类型转换器在运行时读取“Type”值。
这也是{StaticResource foo}如何通过XAML父级查找可能在其中具有“foo”的ResourceDictionary。

例如:

// This markup extension returns the number of Ambient "Resource" properties
// Found in the XAML tree above it.
// The FrameworkElement.Resources property is already marked [Ambient]
public class MyMarkupExtension : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var schemaProvider = serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;
        var ambientProvider = serviceProvider.GetService(typeof(IAmbientProvider)) as IAmbientProvider;
        XamlMember resourcesProperty = new XamlMember(typeof(FrameworkElement).GetProperty("Resources"), schemaProvider.SchemaContext);
        List<AmbientPropertyValue> resources = (List<AmbientPropertyValue>) ambientProvider.GetAllAmbientValues(null, resourcesProperty);
        Debug.WriteLine("found {0} FramewrkElement.Resources Properties", resources.Count);
        return resources.Count.ToString();
    }
}

目标名称是什么?在属性之前你需要知道这个,如何链接它们? - L.Trabacchin

1

我认为MSDN链接在解释这个问题方面做得很好。

另外,请参考上述页面中的这一行:

"环境类型(应用了AmbientAttribute的类型)可用于某些需要按顺序解析属性类型的XAML处理情况。"

而且,链接中提到:

"AmbientAttribute出现在几个WPF类型的成员上,包括Application、Setter和Style。它还出现在ResourceDictionary类型上,这意味着任何使用ResourceDictionary作为其类型的成员都应该被视为环境类型,即使该成员没有明确标记。"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接