Unfortunately, in the current version of the Windows Phone 7 Silverlight framework, it is not possible to attach any command on the applicationbarmenuitem and applicationbarbutton controls. these two controls appear in the application bar, for example with the following markup:
View Source
Print? 01.
<
Phonenavigation: phoneapplicationpage. ApplicationBar
>
02.
<
Shell: ApplicationBar
X: Name
=
"Mainpageapplicationbar"
>
03.
<
Shell: ApplicationBar. menuitems
>
04.
<
Shell: applicationbarmenuitem
05.
Text
=
"Add City"
/>
06.
<
Shell: applicationbarmenuitem
07.
Text
=
"Add Country"
/>
08.
</
Shell: ApplicationBar. menuitems
>
09.
<
Shell: ApplicationBar. Buttons
>
10.
<
Shell: applicationbariconbutton
11.
Iconuri
=
"/Resources/appbar.feature.video.rest.png"
/>
12.
<
Shell: applicationbariconbutton
13.
Iconuri
=
"/Resources/appbar.feature.settings.rest.png"
/>
14.
<
Shell: applicationbariconbutton
15.
Iconuri
=
"/Resources/appbar.refresh.rest.png"
/>
16.
</
Shell: ApplicationBar. Buttons
>
17.
</
Shell: ApplicationBar
>
18.
</
Phonenavigation: phoneapplicationpage. ApplicationBar
>
This code will create the following UI:
Application bar, collapsed
Application bar, expanded
Applicationbaritems are not, however, controls. A quick look in msdn shows the following hierarchy for applicationbarmenuitem, for example:
Unfortunately, this prevents all the mechanisms that are normally used to attach a command (for exampleA relaycommand) To a control. for example, the attached behavior present in the class buttonbaseextension (from the Silverlight 3 version of The mvvm light Toolkit) can only be attached to a dependencyobject. similarly, blend behaviors (such as eventtocommand from the Toolkit's Extras Library) needs a frameworkelement to work.
Using code behind
The alternative is to use code behind.As I said in my mix10 talk, The mvvm police willNotTake your family away if you use code behind (this quote was actually suggested to meGlenn Block); The Code behind is there for a reason. In our case, invoking a command in the viewmodel requires the following code:
In mainpage. XAML:
View Source
Print?1.
<
Shell: applicationbarmenuitem
Text
=
"My menu 1"
2.
Click
=
"Applicationbarmenuitemclick"
/>
In mainpage. XAML. CS
View Source
Print? 01.
Private
Void
Applicationbarmenuitemclick (
02.
Object
Sender,
03.
System. eventargs E)
04.
{
05.
VaR Vm = datacontext
As
Mainviewmodel;
06.
If
(Vm! =
Null
)
07.
{
08.
VM. mycommand. Execute (
Null
);
09.
}
10.
}
Conclusion
resorting to code behind to bridge the gap between the view and the viewmodel is less elegant than using attached behaviors, either through an attached property or through a blend behavior. it does, however, work fine. I don't have any information if future changes in the Windows Phone 7 Application bar API will make this easier. in the mean time, I wocould recommend using code behind instead.