简体   繁体   中英

Using ItemsControl on a multi-leveled TreeView

My co-worker threatened to put me on TheDailyWTF today because of my property I wrote to be used to build a 3-tiered treeview with ItemsControl.

I bear you the footprint:

ObservableCollection<KeyValuePair<string, ObservableCollection<KeyValuePair<string, ObservableCollection<MyType>>>>>;

My goal was to create an ItemsControl that would use the Key as the header, and Value as the ItemsSource for 3 levels:

<Style x:Key="filterTreeStyle" TargetType="ItemsControl">
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <controls:TreeViewItem IsExpanded="True">
                        <controls:TreeViewItem.Header>
                            <controlsToolkit:TreeViewItemCheckBox Content="{Binding Key}"/>
                        </controls:TreeViewItem.Header>
                        <ItemsControl ItemsSource="{Binding Value}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <controls:TreeViewItem>
                                    <controls:TreeViewItem.Header>
                                        <controlsToolkit:TreeViewItemCheckBox Content="{Binding Key}"/>
                                    </controls:TreeViewItem.Header>
                                        <controlsToolkit:TreeViewItemCheckBox IsChecked="{Binding Enabled}" Content="{Binding FilterTypeText}"/>
                                    </controls:TreeViewItem>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </controls:TreeViewItem>
                </DataTemplate>
            </Setter.Value>
        </Setter>
       </Style>

Can anyone save me from the clutches of TheDailyWTF? What is a cleaner way to do this. Bonus if we can figure out a way to make the number of levels dynamic.

Uh, maybe I'm being dumb here, but since you want a TreeView... why not use a TreeView? You'll also need to use a HierarchicalDataTemplate instead of a vanilla DataTemplate: the content of the HDT becomes the Header, and the ItemsSource is used to create the child nodes. That will also take care of making the number of levels dynamic.

TreeView is built into WPF and is available in Silverlight as part of the SDK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM