代码之家  ›  专栏  ›  技术社区  ›  RationalGeek

在XAML中声明的集合挂起Silverlight

  •  4
  • RationalGeek  · 技术社区  · 14 年前

    我一直在玩在XAML中声明对象的游戏。我的Silverlight程序集中有以下类:

    public class TextItem
    {
        public string TheValue { get; set; }
    }
    
    public class TextItemCollection
    {
        public ObservableCollection<TextItem> TextItems { get; set; }
    }
    

    然后,我的XAML中有这个:

    <UserControl.Resources>
        <app:TextItemCollection x:Key="TextItemsResource">
            <app:TextItemCollection.TextItems>
                <app:TextItem TheValue="Hello world I am one of the text values"/>
                <app:TextItem TheValue="And I am another one of those text items"/>
                <app:TextItem TheValue="And I am yet a third!"/>
            </app:TextItemCollection.TextItems>
        </app:TextItemCollection>
    </UserControl.Resources>
    

    出于某种原因,如果在尝试调试应用程序时包含该节点,则Silverlight将挂起(我只看到旋转的蓝色加载圈变薄)。如果我注释掉那个节点,它会立即运行。

    有什么想法吗?

    1 回复  |  直到 14 年前
        1
  •  6
  •   Curt Nichols    14 年前

    按代码检查:您的texteitems属性为空。这对XAML解析器没有帮助。

    通过实验结果:我在调试器中运行应用程序时得到一个异常(我使用的是Silverlight4):

    System.Windows.Markup.XamlParseException occurred
      Message=Collection property '__implicit_items' is null. [Line: 12 Position: 40]
      LineNumber=12
      LinePosition=40
      StackTrace:
           at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
      InnerException: 
    

    您应该初始化textItems。你还应该把setter设为私有,这样别人就不会把你搞砸了。试试这个,你会发现它很好用:

    public class TextItemCollection
    {
        public TextItemCollection()
        {
            TextItems = new ObservableCollection<TextItem>();
        }
    
        public ObservableCollection<TextItem> TextItems { get; private set; }
    }