TreeView- Dynamically Add Items
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: TreeView- Dynamically Add Items

  1. #1
    Join Date
    Dec 2008
    Posts
    144

    TreeView- Dynamically Add Items

    I've never used WPF before, so I'm having some trouble. I'm using VS2008 and coding in C#.

    I've declared a TreeView object in XAML like this:
    Code:
    <Window x:Class="Directory_TreeView.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
        <Grid>
            <TreeView Name="DirectoryTree" HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="260">
                
            </TreeView>
        </Grid>
    </Window>
    Now, I want to populate the treeview when the application loads so that it shows all of the available directories. It will eventually let you drill down to see files in folders, but for now I'm just trying to get the directories to show up.

    This is the code I'm trying to use to populate the treeview
    Code:
    private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                TreeViewItem newChild = new TreeViewItem();
                foreach (DriveInfo di in DriveInfo.GetDrives())
                {
                    newChild.Header = di.Name;
                    parent.Items.Add(newChild);
                }
            }
    The bolded line is where I'm running into trouble- my Parent object does not contain an Items method. Suggestions? Am I going about this the completely wrong way?

  2. #2
    Join Date
    Jan 2010
    Posts
    1,102

    Re: TreeView- Dynamically Add Items

    What is the type of parent?
    Also, I don't think that Add creates a copy of the TreeViewItem object so you may end up with either all the same items in the tree, or an exception thrown (not sure how the class behaves).

  3. #3
    Join Date
    Jan 2011
    Posts
    4

    Re: TreeView- Dynamically Add Items


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center