Question

I have a static Command class like this (but with many more commands):

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; }
}

It should use my dictionary to get the texts in the right language, which doesn't work, because my dictionary isn't initialized when the static constructor is executed.

My first attempt was to create a new command-class which derives from RoutedUICommand, override the Text property and call the dict in the get method. But the Text property isn't virtual and neither is the GetText()-Method it calls.

The only thing i can think of is provide a static initialize method in this class that translates all the dict-keys. But this is not very clean IMHO because i have to name every command once again like this

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

and if i forget to name one, there won't be an error, just no translation. I don't even like that i have to name the command twice in this class and once again in the XAML commandbindings.

Do you have any ideas how this can be solved more elegantly?

I like RoutedUICommands much, but like this they're useless to me. Why couldn't Microsoft add the little word 'virtual' a little more often?? (or make it default like JAVA does?!)

Était-ce utile?

La solution

I found an acceptable way by translating all commands automatically using reflection. This way i at least don't have to add all the commands to another method. I call the translate-method right after i initialized my dictionary.

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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top