Get an ApplicationBarIconButton by name
[Windows Phone 7]
If you want to reference an icon bar button in code, it’s not as straight-forward as you would expect. Though you can use the x:Name attribute, it doesn’t actually create a name in the code-behind. Instead, just enumerate the Buttons collection in the PhoneApplicationPage.ApplicationBar class and compare the Text property. Voila! I wanted to use LINQ, but no dice on the IList type. Also, strangely, the collection of buttons are of type Object, so you need to cast them.
private ApplicationBarIconButton GetAppBarIconButton(string name) { foreach (var b in ApplicationBar.Buttons) if (((ApplicationBarIconButton)b).Text == name) return (ApplicationBarIconButton)b; return null; }
2 Comments
James Curran said
Why are we pointless casting twice ?
foreach (ApplicationBarIconButton b in ApplicationBar.Buttons)
if (b.Text == name)
return b;
Heck, we could even LINQ this:
return ApplicationBar.Buttons.Cast<ApplicationBarIconButton>().FirstOrDefault(b=>b.Text == name);
(The problem is that ApplicationBar.Buttons is an IList when it really should be a IList<ApplicationBarIconButton>
atkulp said
Absolutely right. I always forget about the Cast() method in LINQ. I could have casted the list in the foreach loop for that matter too. Thanks!