需要解决方法来覆盖RoutedUICommand.Text属性

时间:2012-01-24 12:32:16

标签: c# wpf routed-commands

我有一个像这样的静态Command类(但有更多命令):

class GuiCommands
{
    static GuiCommands()
    {
        addInterface = new RoutedUICommand(DictTable.getInst().getText("gui.addInterface"), "addInterface", typeof(GuiCommands));
        removeInterface = new RoutedUICommand(DictTable.getInst().getText("gui.removeInterface"), "removeInterface", typeof(GuiCommands));
    }

    public static RoutedUICommand addInterface { get; private set; }
    public static RoutedUICommand removeInterface { get; private set; }
}

它应该使用我的字典来获取正确语言的文本,这不起作用,因为在执行静态构造函数时我的字典没有被初始化。

我的第一次尝试是创建一个派生自RoutedUICommand的新命令类,覆盖Text属性并在get方法中调用dict。但Text属性不是虚拟的,也不是GetText() - 它调用的方法。

我唯一能想到的是在这个类中提供一个静态初始化方法来转换所有的dict-key。但这不是很干净恕我直言,因为我必须再次命名每个命令,如此

addInterface.Text = DictTable.getInst().getText(addInterface.Text);

如果我忘记命名一个,就不会有错误,也就是没有翻译。 我甚至不喜欢我必须在这个类中命名两次命令,再次在XAML命令绑定中命名。

你有什么想法可以更优雅地解决这个问题吗?

我非常喜欢RoutedUICommands,但是像这样他们对我没用。为什么微软不能经常添加“虚拟”这个小词? (或者像JAVA一样默认吗?!)

1 个答案:

答案 0 :(得分:0)

我通过使用反射自动翻译所有命令找到了一种可接受的方法。 这样我至少不必将所有命令添加到另一个方法。 我在初始化词典后立即调用了translate-method。

public static void translate()
{
    // get all public static props
    var properties = typeof(GuiCommands).GetProperties(BindingFlags.Public | BindingFlags.Static);

    // get their uicommands
    var routedUICommands = properties.Select(prop => prop.GetValue(null, null)).OfType<RoutedUICommand>(); // instance = null for static (non-instance) props

    foreach (RoutedUICommand ruic in routedUICommands)
        ruic.Text = DictTable.getInst().getText(ruic.Text);
}