代码之家  ›  专栏  ›  技术社区  ›  Igor Zevaka

XAML如何设置只读CLR属性?

  •  3
  • Igor Zevaka  · 技术社区  · 14 年前

    我正在尝试用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 属性没有set访问器,定义如下:

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

    为什么这可以在XAML中完成而不是C?是否有一种特殊的方法可以使用这种语法构造对象?

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

    3 回复  |  直到 14 年前
        1
  •  4
  •   Charlie    14 年前

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

    直接添加到 Buttons 属性。

        2
  •  2
  •   dthorpe    14 年前

    它可能使用buttons.add而不是赋值给buttons属性。

        3
  •  1
  •   Simon Fox    14 年前

    这个 ApplicationBar.Buttons 成员具有添加函数(请参见 this )

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