开发者

WPF TreeView question

Is it possible to store some data in every item of a TreeView control? I mean, something useful (e.g. a string) besides the header text? Tha开发者_如何转开发nks.


Yes, WPF is "lookless", so your actual data can be anything you want it to be, and a TreeView is just a Template used to display the data to the user in a pre-determined way.

You can overwrite any part of that Template to be whatever you want, and/or have it bind to your data however you want.

Edit

I'm no expert on using the TreeView, but if you had a DataContext of List<Folder>, and each Folder object had a Name and a FullPath property, your TreeView could look something like this:

<TreeView ItemsSource="{Binding MyFolderList}">
    <TreeView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"
                       ToolTip="{Binding FullPath}" />
        </DataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

If you haven't already, I'd highly recommend looking into the MVVM design pattern when working with WPF. Basically your application is your classes (ViewModels), and the Controls/XAML (Views) are just a pretty layer that sits on top of your classes to make them user-friendly.

This is an important concept when switching from a WinForms TreeView to a WPF TreeView


It depends on what you mean by store data...

If you're just talking UI customization Rachel's answer above works.

If you're talking about storing arbitrary object values, such as information about the TreeViewItem, or maybe a relation between two items, you can use the Tag property of TreeViewItem. For example, I had to write a mapping UI where two trees linked together where each TreeViewItem from the first tree, could connect to 1 TreeViewItems of the second tree. I used the Tag property of the first TreeViewItem to store the connecting TreeViewItem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜