Retrieving a Button or Menu Item at Runtime

,

Although the built-in application bar allows you to assign names to buttons and menu items in XAML using the x:Name attribute, the CLR runs into trouble resolving items by name at runtime. Consider the following example:

<phoneNavigation:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>
        <shell:ApplicationBar.Buttons>
            <shell:ApplicationBarIconButton
                IconUri="/Images/Play.png"
                Click="OnPlayButtonClick" />
            <shell:ApplicationBarIconButton
                x:Name="PauseButton"
                IconUri="/Images/Pause.png"
                Click="OnPlayButtonClick"
                IsEnabled="True" />
        </shell:ApplicationBar.Buttons>
    </shell:ApplicationBar>
</phoneNavigation:PhoneApplicationPage.ApplicationBar>

When the PlayButton is tapped, it raises the Click event, calling the OnPlayButtonClick method:

void PlayButtonClick(object sender, EventArgs e)
{
    PauseButton.IsEnabled = true; /* Fails, PauseButton is always null */
}

This, however, raises a NullReferenceException because the named PauseButton is always null. This occurs despite Visual Studio providing IntelliSense for the named item. Thus, you cannot refer to an ApplicationBarIconButton or an ApplicationBarMenuItem by name in the code-beside. Instead, the ApplicationBar.Buttons property must be used to resolve a button, as shown:

void PlayButtonClick(object sender, EventArgs e)
{
    ApplicationBar.Buttons[1].IsEnabled = true;
}

This example highlights an earlier point regarding difficulties associated with the ApplicationBar being outside the visual tree. It is an awkward class to develop with, and it has various limitations that make it a likely candidate for improvement in the future. In the meantime, however, I have created a wrapper for the class that behaves more as you would expect, yet possesses an almost identical API as the built-in ApplicationBar. The name of this custom wrapper class is AppBar, and it is the focus of the rest of this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.192.234