There are some navigational paradigms out there that use navigation strings to hit, in turn, methods within your own codebase. It’s a sound idea, but generating those URIs as strings which you in turn use in a Navigate() call can be problematic. What happens when you add a parameter to the method? Rearrange the parameters? And what if you could get intellisense when you wanted to generate those URIs?
Look no further than that awesomeness Microsoft provides us .Net developers than the beautiful acronym we all love: LINQ. More specifically, the Expression Tree objects that we got with LINQ.
I’ve used a pretty handy class for a while now that allow me to use hard references to properties when I am implementing/calling
INotifyPropertyChanged objects. Basically, it turns
which, as you can guess, makes sure that I never misspell the property and also never use one that’s not available in my code.
So, I took this idea another step and dissected the handy reusable file I’d had in so many of my Windows Phone projects to accomplish this to see if I could make it fit the bill of a NavigationURI generator.
Here’s what I came up with:
public static string CreateStringForCall<T>(Expression<Action<T>> methodCall)
var exp = methodCall.Body as MethodCallExpression;
var retVal = string.Concat(exp.Method.Name, "/",
string.Join("/", exp.Arguments.Cast<ConstantExpression>().Select(a => a.Value.ToString())));
which gets used like this:
public class SubClass
public void MyMethod(string name, int value)
static void Main(string args)
and gives me this:
Pretty slick! Feel free to dissect the expression tree magic going on here and augment it to your liking!