简体   繁体   中英

Access to environment variables by xaml code

It is possible to access somehow ONLY via xaml code to an environment variable? In my case, I only need the read access.

You can write a custom markup extension. Something like:

[MarkupExtensionReturnType(typeof(String))]
public class EnvironmentVarExtension : MarkupExtension
{
    private string _variableName;

    public EnvironmentVarExtension(string variableName)
    {
        _variableName = variableName;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Environment.GetEnvironmentVariable(VariableName);
    }

    [ConstructorArgument("variableName")]
    public string VariableName
    {
        get { return _variableName; }
        set { _variableName = value; }
    }
}

And use it in your XAML:

<Grid>
    <TextBlock Text="{local:EnvironmentVar Path}" />
</Grid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM