【问题标题】:Binding a nested List in XAML在 XAML 中绑定嵌套列表
【发布时间】:2016-04-06 17:13:30
【问题描述】:

我的 ViewModel 如下所示:

public class MainViewModel : BaseViewModel
{
    public List<Paragraph> Paragraphs { get; set; }
    . . .
}

public class Paragraph
{
    public List<ParagraphElement> Elements; 
    . . .
}

我的 XAML 看起来像这样:

    <StackPanel Grid.Row="1">
        <ItemsControl ItemsSource="{Binding Paragraphs}">
            <ItemsControl ItemsSource="{Binding Elements}" ItemTemplate="{StaticResource ParagraphElements}" />
        </ItemsControl>
    </StackPanel>   

我收到以下错误: "XamlParseException"

以及附加信息: '向'System.Windows.Controls.ItemCollection'类型的集合添加值 抛出异常。'

如何在 XAML 中绑定这个嵌套结构?

【问题讨论】:

    标签: c# .net wpf xaml data-binding


    【解决方案1】:

    您必须为外部 ItemsControl 设置 ItemTemplate。抛出异常是因为您为外部 ItemsControl 设置了 ItemsSource 并同时向 Items 集合添加了内部 ItemsControl

    <StackPanel Grid.Row="1">
        <ItemsControl ItemsSource="{Binding Paragraphs}">
            <ItemsControl.ItemTemplate>
            <DataTemplate> 
              <Border BorderThickness="1" BorderBrush="Green">
                 <ItemsControl ItemsSource="{Binding Elements}" 
                               ItemTemplate="{StaticResource ParagraphElements}" />
              </Border>
            </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>  
    

    【讨论】:

    • 现在我没有收到错误。但除了 n 个带有绿色边框的矩形外,我什么也没看到,其中 n = 段落数。
    • @moller1111,在您的示例中,public List&lt;ParagraphElement&gt; Elements; 是一个字段。 Binding 需要一个属性,输出窗口中应该有一条关于绑定错误的消息。像这样更改您的代码:public List&lt;ParagraphElement&gt; Elements {get;set;}(类似于Paragraphs)。第一次没注意到
    猜你喜欢
    • 2011-03-28
    • 2014-05-02
    • 2020-03-14
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多