Search This Blog

Wednesday, October 30, 2013

Programmatically fill TreeView items WPF

WPF > ItemsControl > TreeView > Add items to TreeView

Example of programmatically add items to TreeView control in WPF.

XAML:

        <TreeView x:Name="tvMain"  Grid.Column="0">
            <TreeView.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}">
                    <EventSetter Event="MouseLeftButtonUp" Handler="treeViewItem_MouseLeftButtonUp"/>
                </Style>
            </TreeView.ItemContainerStyle>
        </TreeView>

 
Code:
 
  // fill Tree

            TreeViewItem tviSet = new TreeViewItem() { Header = "Settings"  };
            TreeViewItem tviProd = new TreeViewItem() { Header = "Products" };
            tviProd.Tag = "Products";

            TreeViewItem tviComp = new TreeViewItem() { Header = "Companies" };
            tviComp.Tag = "Companies";

            tviSet.Items.Add(tviProd);
            tviSet.Items.Add(tviComp);
            tviSet.IsExpanded = true;

            tvMain.Items.Add(tviSet);