我在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);
}
}
}
它允许我编写如下代码:<TextBlock Text="{GetString txt_login}" />
在我可以使用这个类之前,我必须初始化ResourceManager。我在应用程序启动时这样做。一切正常,除了我不能使用设计器 - 它总是会抛出InvalidOperationException。有没有办法在设计器尝试实例化之前初始化这个类?
答案 0 :(得分:0)
一个选项是向此类添加属性,或者在某个静态类中添加属性,如下所示:
public bool IsDesignTime
{
get
{
return (System.Windows.Application.Current == null) || (System.Windows.Application.Current.GetType() == typeof(System.Windows.Application));
}
}
然后修改你的扩展名:
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);
}
另一个选项是,只要初始化此类中的ResourceManager,如果它为null。要么有效。