Reputation: 13620
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?
Upvotes: 0
Views: 965
Reputation: 7243
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!!!
Upvotes: 1
Reputation: 2140
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);
}
Upvotes: 1
Reputation: 84824
Try removing the x:Name
property and access it using Page.ApplicationBar.
Upvotes: 1