XAML如何设置只读的CLR属性?

3

我正在尝试为WinPhone7创建一个应用程序栏。实现它的XAML代码如下:

<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属性没有设置访问器,并且定义如下:
public sealed class ApplicationBar {
  //...Rest of the ApplicationBar class from metadata
  public IList Buttons { get; }
}

为什么可以在XAML中实现这个功能,而在C#中却不能?使用这种语法构建对象的方式有什么特殊之处吗?

更重要的是,我该如何在代码中重新创建它?

3个回答

4

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

直接添加到Buttons属性中。


2
它可能使用Buttons.Add而不是分配给Buttons属性。

是的,列表是可变的,因此您不必重新分配引用,因此它们被设置为只读以避免不良副作用。 - Earlz

1

ApplicationBar.Buttons 成员有一个 Add 函数(请参见 this

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

appBar.Buttons.Add(appBarButton);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接