2010-04-12 96 views
3

我想在WinPhone7的代碼中創建一個應用程序欄。 ,做它的XAML是這樣的:XAML如何設置只讀CLR屬性?

<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> 

所以我想我只是把它改寫在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 

唯一的問題是,Buttons屬性沒有set訪問並定義如下:

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

這是怎麼來的,可以在XAML而不是C#?有沒有一種特殊的方式來使用這種語法構造對象?

更重要的是,我該如何在代碼中重新創建它?

回答

4

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

直接添加到Buttons財產。

+0

衛生署!感謝那。 – 2010-04-12 23:58:42

2

它可能使用Buttons.Add而不是分配給Buttons屬性。

+0

是的。列表是可變的,所以您不必重新分配引用,因此它們使其只讀以避免令人討厭的副作用 – Earlz 2010-04-12 23:50:40

1

ApplicationBar.Buttons部件具有添加功能(參見this

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

appBar.Buttons.Add(appBarButton);