古事連記帖

趣味のこと、技術的なこと、適当につらつら書きます。

ApplicationBarの不思議なお話

Windowsアプリでいう「ツールバー」や「メニューバー」のような感じで使える、Windows Phone 7での画面下に現れるバーのお話。
結構便利なのでいろいろ使いたいところではありますが、ちょっとだけ注意が必要かも。

ApplicationBarってこういう奴です。


XAMLを使って、Expression Blendを駆使して作るとめちゃくちゃ楽です。ApplicationBarIconButtonですとアイコンも一覧から選べる上に勝手にリソースに追加してくれます。

例えばXAMLでこういう記述をしておきます。

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton x:Name="favButton" IconUri="/icons/appbar.favs.rest.png" Text="ふぁぼ"/>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem x:Name="settingMenu" Text="設定"/>
        </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

ビルドしてVisualStudioのコード画面で、favButtonとsettingMenuにアクセスできることを確認しておきます。


適当な場所でブレークポイント置いた後に、実機でもエミュレーターでもいいので実行して、止まった時にfavButtonとsettingMenuそれぞれの状態を確認してみると、なんということでしょう。全部nullになっています。
他のTextBlockコントロールなどはちゃんと実体があるのでアクセスできますが、なぜかApplicationBarにのったものはアクセスできないのです。


どうやらApplicationBarの領域は別扱いになっているようです。


ではどうすればいいかというと、2つほど方法があります。
先ほどのツイートのように、コード上で実装してしまう方法があります。

ApplicationBarIconButton favoriteButton = new ApplicationBarIconButton();
favoriteButton.IconUri = new Uri("/icons/appbar.favs.rest.png", UriKind.Relative);
favoriteButton.Text = "お気に入り";

ApplicationBarMenuItem setMenu = new ApplicationBarMenuItem();
setMenu.Text = "設定";

this.ApplicationBar.Buttons.Add(favoriteButton);
this.ApplicationBar.MenuItems.Add(setMenu);

もう一つは、 順番がわかっていればコレクションから直接取り出す方法もあります。

((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).IsEnabled = true;
((ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0]).IsEnabled = true;

thanks:


どちらがいいかは使い方次第ってところです。