我们经常会把command封装在MVVM中,然后在xaml中通过绑定访问。
例如,我们xaml中有一个Button,我们可能会这样(前提是我们设置了页面的DataContext为mvvm)
<Button Content="LoadData" Command="{Binding LoadDataCommand}" />
但是,windows phone中的ApplicationBar中的button和menu没有Command属性,所以我们一定会想到event to command的转换!
小注:event to command转换不难理解,我们都知道event是时间,它可以启动一个trigger(系统支持),而trigger启动又可以执行一个action,我们只需要在action中调用相应的command即可。
于是,如果你使用GalaSoft的mvvm light框架的话,自然而然会想到以下代码:
但是,如果你编译此代码,它会报错:Code:<phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"> <shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/icons/appbar.questionmark.rest.png" Text="About"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <GalaSoft_MvvmLight_Command: EventToCommand Command="{Binding DisplayAbout, Mode=OneWay}" /> </i:EventTrigger> </i:Interaction.Triggers> </shell:ApplicationBarIconButton> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem x:Name="menuItem1" Text="MenuItem 1"></shell:ApplicationBarMenuItem> <shell:ApplicationBarMenuItem x:Name="menuItem2" Text="MenuItem 2"></shell:ApplicationBarMenuItem> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar>
ApplicationBarIconButton和ApplicationBarMenuItem不是DependencyObject,不能使用interactivity。。。
所以,这条路就不同了。
查了些资料,有人已经为我们解决了这一问题,就是BindableApplicationBar,
大家可以在这里下载:
http://bindableapplicationb.codeplex.com/
BindingableApplicationBar的原理并不是很复杂,其实就是把原来的ApplicationBar封装成了Control,ApplicationBarIconButton、ApplicationBarMenuItem封装为FrameworkElement。而Control和FrameworkElement都是继承自DependencyObject的,自然就可以使用interactivity了。。。
Regards
Vincent
http://weibo.com/xueyw

Reply With Quote

