因為ApplicationBar並不支援資料繫結,所以做MVVM的時候是個麻煩。經過今天的研究終於搞定的了。
我們需要的是一個第三方dll:
AppBarUtils 大牛Allen Lee的。:http://appbarutils.codeplex.com
不過目前所提供的功能來看只支援Text跟Command的綁定,於是我下載源碼下來修改了一下,使之支援了IconUri綁定。這就不貼代碼了,直接提供改過的dll。
使用:
添加xmlns:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:AppBarUtils="clr-namespace:AppBarUtils;assembly=AppBarUtils"
在XAML添加:
<phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" > <shell:ApplicationBarIconButton IconUri="/icon/f.png" Text="test" /> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar> <i:Interaction.Behaviors> <AppBarUtils:AppBarItemCommand Id="test" Text="{Binding BtnName}" IconUri="{Binding ImgUri}" Command="{Binding ChangeAppBarBtnImg}" /> </i:Interaction.Behaviors>
VM:
public class MainPageViewModel : ViewModelBase { public MainPageViewModel() { ChangeAppBarBtnImg = new RelayCommand(ChangeImg); } private string _BtnName="OK"; public string BtnName { get { return _BtnName; } set { this._BtnName = value; this.RaisePropertyChanged("BtnName"); } } private Uri _ImgUri = new Uri("/icon/f.png", UriKind.Relative); public Uri ImgUri { get { return _ImgUri; } set { _ImgUri = value; this.RaisePropertyChanged("ImgUri"); } } private RelayCommand _ChangeAppBarBtnImg; public RelayCommand ChangeAppBarBtnImg { get { return _ChangeAppBarBtnImg; } set { _ChangeAppBarBtnImg = value; this.RaisePropertyChanged("ChangeAppBarBtnImg"); } } private void ChangeImg() { if (this.ImgUri.OriginalString == "/icon/f.png") { this.ImgUri = new Uri("/icon/s.png", UriKind.Relative); } else { this.ImgUri = new Uri("/icon/f.png", UriKind.Relative); } } }
這樣就可以使AppliactionBar支援綁定了。
樣本下載:/Files/kklldog/WP7ApplicationBarBinding.rar