views:

106

answers:

3

I am trying to create an application bar in code for WinPhone7. The XAML that does it goes like this:

<PhoneApplicationPage.ApplicationBar>
    <shellns:ApplicationBar Visible="True" IsMenuEnabled="True">
        <shellns:ApplicationBar.Buttons>
            <shellns:ApplicationBarIconButton IconUri="/images/appbar.feature.search.rest.png" />
        </shellns:ApplicationBar.Buttons>
    </shellns:ApplicationBar>
</PhoneApplicationPage.ApplicationBar>

So I thought I'd just rewrite it in C#:

var appbar = new ApplicationBar();
var buttons = new List<ApplicationBarIconButton>();
buttons.Add(new ApplicationBarIconButton(new Uri("image.png", UrlKind.Relative));
appbar.Buttons = buttons; //error CS0200: Property or indexer 'Microsoft.Phone.Shell.ApplicationBar.Buttons' cannot be assigned to -- it is read only

The only problem is that Buttons property does not have a set accessor and is defined like so:

public sealed class ApplicationBar {
  //...Rest of the ApplicationBar class from metadata
  public IList Buttons { get; }
}

How come this can be done in XAML and not C#? Is there a special way that the objects are constructed using this syntax?

More importantly, how can I recreate this in code?

+4  A: 

appbar.Buttons.Add(new ApplicationBarIconButton(new Uri("image.png", UrlKind.Relative));

Add directly to the Buttons property.

Charlie
Doh! Thanks for that.
Igor Zevaka
+2  A: 

It probably uses Buttons.Add instead of assigning to the Buttons property.

dthorpe
yep. lists are mutable, so you don't have to reassign the reference, hence they made it read-only to avoid nasty side-effects
Earlz
+1  A: 

The ApplicationBar.Buttons member has an Add function (see this)

var appBarButton = 
           new ApplicationBarIconButton(new Uri("image.png", UrlKind.Relative)

appBar.Buttons.Add(appBarButton);
Simon Fox