豆瓣电台WP7客户端 MVVM重构记录之使用AppBarUtils使ApplicationBarIconButton支持绑定(包括IconUri)

因为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

QQ群:1022985150 VX:kklldog 一起探讨学习.NET技术
作者:Agile.Zhou(kklldog)
出处:http://www.cnblogs.com/kklldog/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/kklldog/p/2380726.html