【问题标题】:Create list of check boxes inside list of groupboxes dynmically动态创建组框列表内的复选框列表
【发布时间】:2016-12-19 13:23:41
【问题描述】:

当每个组内都有一个复选框列表时,我需要创建一个组框列表,所有这些都是动态加载的。 我创建了将所有复选框插入所有组框的虚拟机:

ObservableCollection<GroupBox> Groups = new ObservableCollection<GroupBox>();
GroupBox group = new GroupBox();
ObservableCollection<CheckBox> content= new  ObservableCollection<CheckBox>();
group.content = content;
Content.Add(new checkBox());
Content.Add(new checkBox());
.
.
.

我的 xaml 看起来像这样:

<ItemsControl ItemSource = "{Binding Groups}">
    <ItemsControl ItemSource = "{Binding Content}">
    </ItemsControl
</ItemsControl>

如果我只绑定到组:我得到很好的组框,但是当我在里面添加 itemsControl 时,它不起作用。

我得到:“在使用 ItemsSource 之前,项目集合必须为空”

我哪里出错了? TX Tal

【问题讨论】:

  • 如果每个组都有自己的复选框列表,那么您需要为您的组创建GroupViewModel,在其中您将有一个List&lt;Checkbox&gt;。然后你会有一个&lt;ItemsControl&gt;GroupViewModel 和第二个&lt;ItemsControl&gt;List&lt;GroupViewModel&gt; 在你的父母ViewModel
  • 在这里查看接受的答案:social.msdn.microsoft.com/Forums/vstudio/en-US/…。我认为您正在混合您的模型/视图。您的模型数据应该是一个以字符串为键(组框名称)的字典,并且每个项目都是一个包含布尔值的结构。在您的 xaml 中,您应该指出每个外部项目创建一个组框,每个内部项目表示为一个复选框。

标签: wpf


【解决方案1】:

如果我只绑定到组:我得到了很好的组框,但是当我在里面添加 itemsControl 时,它不起作用。 我得到:“在使用 ItemsSource 之前,项目集合必须为空”

这是因为内部 ItemsControl 被视为外部 ItemsControl 的子级,因此当您尝试设置 ItemsSource 时会引发异常。

对于多级,您需要按照 o_weisman 所说或如下所示设置 DataTemplate,

 <ItemsControl ItemsSource="{Binding Groups}">
            <ItemsControl.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Content}">
                    <!--control you need to display-->
                </HierarchicalDataTemplate> 
            </ItemsControl.ItemTemplate>
        </ItemsControl>

【讨论】:

    猜你喜欢
    • 2016-12-21
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    相关资源
    最近更新 更多