在选择上使用动态内容填充WPF列表框子项

时间:2014-06-04 05:04:14

标签: wpf listbox wpf-controls

我正在尝试实现UI方案。它用于表示目录,与MainChapter,Sub chapter,Sub-sub chapter等结构的树状结构 类表示更像是

MainChapters
 Name 
 Prop1
 Prop2
 List<SubInfo>

SubInfo 
 List<Pages>

Pages
  Name  
  List<MediaElements>
  List<SubInfo>

MediaElement 
   Name 
   Type

我计划实现的UI是将MainChapters绑定到列表框,一旦选择了列表框中的特定项目,我计划将SubInfo作为子项绑定到Listbox 设计要求如附图所示 ![预期用户界面的样本结构] [1]

所以我可以将WPF Listbox用于上述类型的UI实现或任何其他建议或最简单的方法吗?

1 个答案:

答案 0 :(得分:2)

这里有一个示例,在此示例中,我使用ListBoxItem的IsSelected属性控制子组的可见性

    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness=".5" Padding="1">
                    <StackPanel>
                        <TextBlock Text="{Binding}" />
                        <GroupBox Header="child group" MaxHeight="100"
                                  Visibility="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Converter={StaticResource BooleanToVisibilityConverter}}">
                            Child data
                        </GroupBox>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.Items>
            <sys:DateTime />
            <sys:DateTime />
            <sys:DateTime />
        </ListBox.Items>
    </ListBox>

点击鼠标隐藏子面板

  • 添加了一个切换按钮作为标题
  • 从按钮替换原始模板以获得所需的外观
  • 将IsChecked属性绑定到ListBoxItem的IsSelected
  • 将子面板可见性的绑定修改为更短的语法

它有一个切换按钮来隐藏子内容

    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness=".5" Padding="1">
                    <StackPanel>
                        <ToggleButton x:Name="toggleChild" Content="header text, click to close" 
                                      IsChecked="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}">
                            <ToggleButton.Template>
                                <ControlTemplate TargetType="ToggleButton">
                                    <ContentPresenter />
                                </ControlTemplate>
                            </ToggleButton.Template>
                        </ToggleButton>
                        <GroupBox Header="child group" MaxHeight="100" 
                                  Visibility="{Binding IsChecked, ElementName=toggleChild, Converter={StaticResource BooleanToVisibilityConverter}}">
                            Child data
                        </GroupBox>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.Items>
            <ListItem />
            <ListItem />
            <ListItem />
        </ListBox.Items>
    </ListBox>