在.NET中使用Ambient属性?

时间:2011-07-11 07:08:59

标签: c# xaml serialization c#-4.0

有人可以了解.NET中的环境属性吗?

2 个答案:

答案 0 :(得分:2)

它用于解决像<Setter Property="P" Value="V" />
这样的问题 在了解如何将V形式转换为正确类型的值之前,您必须知道P(实际上是P的类型)。 使用[Ambient]和1标记“Property”属性。加载器将首先处理“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();
    }
}

答案 1 :(得分:1)

我认为MSDN link擅长解释这一点。

另见上页

中的这一行

“Ambient类型(在类型级别应用AmbientAttribute的类型)可用于某些XAML处理情况,其中需要无序地解析属性的类型。”

link

“AmbientAttribute可以在几个WPF类型的成员上找到,包括Application,Setter和Style。它也可以在ResourceDictionary类型中找到,它意味着任何使用ResourceDictionary作为其类型的成员都应被视为环境,即使成员没有具体归因。“