简体   繁体   中英

How to initialize class for XAML designer in VS 2010?

I have following markup extension defined in Utils.dll

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "Whatever")]
namespace Whatever
{
    public class GetString : MarkupExtension
    {
        public static ResourceManager ResourceManager { get; set; }
        public string Key { get; set; }

        public GetString(string key)
        {
            Key = key;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (ResourceManager == null) 
                throw new InvalidOperationException();
            return ResourceManager.GetString(Key);
        }
    }
}

It allows me to write code like this: <TextBlock Text="{GetString txt_login}" />

Before I can use this class I have to initialize ResourceManager. I do it at application startup. Everything works fine except I can't use designer - it will always throw InvalidOperationException. Is there a way to initialize this class before designer tries to instantiate it?

One option is to add a property to this class, or in a static class somewhere as follows:

public bool IsDesignTime
{
    get
    {
       return (System.Windows.Application.Current == null) || (System.Windows.Application.Current.GetType() == typeof(System.Windows.Application));
    }
}

Then modify you Extension:

public override object ProvideValue(IServiceProvider serviceProvider)
{
    if (IsDesignTime)
    {
        // add code to init resource manager for design time
    }
    if (ResourceManager == null) 
        throw new InvalidOperationException();
    return ResourceManager.GetString(Key);
}

The other option, is to just initialize the ResourceManager in this class if it's null. Either works.

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