c# - 如何在 VS 2010 中为 XAML 设计器初始化类?

标签 c# .net wpf visual-studio xaml

我在 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/

相关文章:

C# 编译器错误 CS0433

c# - 如何声明所需类型以避免 ".. Ambigious reference.."

.net - Entity Framework 实体更新忽略时间戳

.net - 为什么 VB.NET 退出此正则表达式线程? "The thread has exited with code 0"

c# - WPF 使用 € 符号将字符串格式化为货币

wpf - StopStoryboard 不会...停止 BeginStoryboard

c# - ReadLine() 无法读取整行

c# - Apache Ignite.NET 和 AppDomain.CurrentDomain.ProcessExit

c# - 什么是白标 dll 的好方法

C# - 将所有方法参数传递给另一个方法?