简体   繁体   中英

Changing the buttons in the Applicationbar?

I want to change the icons and what they do in code in my WP7 application. I've tried in the MainPage constructor and in the MainPage_Loaded but it says ApplicationBar ( x:Name ) is null all the time.

How can I change it since I use same page and different states?

尝试删除x:Name属性,然后使用Page.ApplicationBar对其进行访问

Unfortunately the application bar buttons are not accessible via code at the moment. I followed one of the examples of the official Mircosoft Training Kit for WP7 to accomplish that task. Here is the XAML and some code:

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>
        <shell:ApplicationBarIconButton IconUri="/icons/appbar.pin.png" IsEnabled="True" Text="Anpinnen" x:Name="appPinPage" Click="appPinPage_Click" />
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Please note that ApplicationBar is a property of PhoneApplicationPage so that you do not have to give an explicit name to the ApplicationBar object that you assign to the ApplicationBar property of the PhoneApplicationPage. Here is an example of changing the picture of the button in the xaml code above. That code is called in the overridden OnNavigatedTo() method of the PhoneApplicationPage.

        if (this.ViewModel.IsPinned())
        {
            ((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).Text = Resource1.txtUnpin;
            ((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).IconUri = new Uri("/icons/appbar.unpin.png", UriKind.Relative);
        }
        else
        {
            ((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).Text = Resource1.txtPin;
            ((ApplicationBarIconButton)this.ApplicationBar.Buttons[0]).IconUri = new Uri("/icons/appbar.pin.png", UriKind.Relative);
        }

Unfortunately, the ApplicationBar isn't a Silverlight control (doesn't inherit from UIElement ); what that means is that it can't be accessed with a x:Name neither the buttons inside it, but you can access it inside the page using the ApplicationBar property!

Check this sample to see how you can create and access the ApplicationBar from the code behind of a page.

If you are willing to go with an MVVM architecture, you should check the ApplicationBarBehaviour from the Cimbalino Windows Phone Toolkit , it will save you a lot of work!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM