【问题标题】:Collection declared in XAML hangs SilverlightXAML 中声明的集合挂起 Silverlight
【发布时间】:2010-08-05 18:31:49
【问题描述】:

我一直在玩在 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 会挂起(我只看到旋转的蓝色加载圆圈)。如果我注释掉那个节点,它会立即运行。

有什么想法吗?

【问题讨论】:

  • 您是否尝试过在 App.xaml 的 UnhandledException 处理程序中放置断点? VS 会在 SL 应用程序的某些部分错过异常,但如果您在 Application.UnhandledException 处理程序的开头中断,您将能够看到正在抛出的异常。
  • 好主意。但不,它只是旋转,我从未达到断点。

标签: silverlight xaml


【解决方案1】:

通过代码审查:您的 TextItems 属性为空。这对 XAML 解析器没有帮助。

通过实验结果:在调试器中运行应用程序时出现异常(我使用的是 Silverlight 4):

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。您还应该将设置器设为私有,这样其他人就不会弄乱您了。试试这个,你应该会发现它工作正常:

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

    public ObservableCollection<TextItem> TextItems { get; private set; }
}

【讨论】:

  • 感谢您的信息。那么在 XAML 中没有办法做到这一点吗?我试图避免代码隐藏。这主要是实践 XAML 的思想实验,而不是实际的生产问题。
  • 我所做的只是修改您的 TextItemCollection 类以使其正常工作。将我的 TextItemCollection 换成你的,你的资源标记应该可以工作。我并不是建议你在后面的代码中这样做;你不需要。
  • 明白了。我明白你现在在说什么了。不幸的是,我已经完全超越了那个例子,所以我不能再重现这个问题了。但我会把答案归功于你,因为可能就是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多