【问题标题】:How does XAML set readonly CLR properties?XAML 如何设置只读 CLR 属性?
【发布时间】:2010-04-12 23:39:10
【问题描述】:

我正在尝试在 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# 中完成?有没有一种特殊的方法可以使用这种语法构造对象?

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

【问题讨论】:

    标签: wpf xaml windows-phone-7


    【解决方案1】:

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

    直接添加到Buttons 属性。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 是的。列表是可变的,因此您不必重新分配引用,因此它们将其设为只读以避免讨厌的副作用
      【解决方案3】:

      ApplicationBar.Buttons 成员具有添加功能(请参阅this

      var appBarButton = 
                 new ApplicationBarIconButton(new Uri("image.png", UrlKind.Relative)
      
      appBar.Buttons.Add(appBarButton);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多