开发者

Use of Ambient attribute in .NET?

Can s开发者_运维知识库omebody please shed light on Ambient Attribute in .NET?


It is used to solve the problem like
<Setter Property="P" Value="V" />
You must know P (actually the type of P) before you can understand how to typeconvert V into a value of the right type. You mark the "Property" property with [Ambient] and 1. the loader will process "Property" first and 2. allows the "Value" type converter to read the "Type" value when it runs.
This is also how {StaticResource foo} looks up through the XAML parents looking for ResourceDictionary's that might have "foo" in them.

For example:

// 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();
    }
}


I think the MSDN link is good at explaining this.

Also see this line in the above page

"Ambient types (types where AmbientAttribute is applied at type level) can be used for certain XAML processing situations where the type of a property needs to be resolved out of order."

And this link says

"AmbientAttribute is found on members of several WPF types, which include Application, Setter, and Style. It is also found on the ResourceDictionary type, which connotes that any member that uses ResourceDictionary as its type should be considered ambient even if the member is not specifically attributed."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜