我在 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。有没有办法在设计器尝试实例化它之前初始化这个类?
最佳答案
一个选项是向此类添加一个属性,或者在某个静态类中添加一个属性,如下所示:
public bool IsDesignTime
{
get
{
return (System.Windows.Application.Current == null) || (System.Windows.Application.Current.GetType() == typeof(System.Windows.Application));
}
}
然后修改你的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);
}
另一种选择是,如果 ResourceManager 为 null,则仅在此类中初始化 ResourceManager。两者都有效。
关于c# - 如何在 VS 2010 中为 XAML 设计器初始化类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8343452/