[英]How to initialize class for XAML designer in VS 2010?
I have following markup extension defined in Utils.dll 我在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}" />
它允许我编写如下代码:
<TextBlock Text="{GetString txt_login}" />
Before I can use this class I have to initialize ResourceManager. 在使用此类之前,必须先初始化ResourceManager。 I do it at application startup.
我在应用程序启动时执行此操作。 Everything works fine except I can't use designer - it will always throw InvalidOperationException.
一切正常,除非我不能使用设计器-它将始终抛出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. 另一个选择是,如果它为null,则只在此类中初始化ResourceManager。 Either works.
无论哪种。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.