Search code examples
c#wpfdata-binding

How to bind an array to custom indexer?


I have a singleton localization class with an indexer. You can access it like this:

Localize.Current[String key]

I also have a custom Binding class that transforms string into a call to this indexer:

{Translate MyKey}

This will set Mode (OneWay) on my the binding, source to Localize.Current (singleton) and also path to:

[$key$]

Where $key$ is evaluated to MyKey. Then it is localized and replaced by a localized value. Now I want to parameterize this binding with additional parameters. So I did this:

Localize.Current[String key, params String[] parameters]
{Translate MyKey, MyParameter1, MyParameter2}

I don't know how to set path in the binding to this, I've tried:

new PropertyPath("[$key$, (0)]", values) // where values is String[] from Translate

This doesn't trigger the indexer. It triggers the Localize.Current[String key, String parameter] indexer, if I add one, but not an arbitrary amount of arguments. I need a path that contains reference to array something like:

new PropertyPath("[$key$, $array_placeholder$], values)

Can't finding anything anywhere. Neither in documentation, nor Google. Anyone has experience how to achieve this? What to put instead of $array_placeholder$?


Solution

  • The PropertyPath constructor with path and parameters is defined like this.

    public PropertyPath (string path, params object[] pathParameters);
    

    The pathParameters argument is an array that holds an object for each index in your path. That means in order to pass your values array for the index zero in your property path, it has to be the first value in the parameters array. Then, the appropriate indexer will be called.

    new PropertyPath("[$key$, (0)]", new object[] {values});
    

    If you pass values directly, the index zero in the path will get the first value of that array, a string.