Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill treeview in WPF dynamically

Treeview code on xaml

<Window x:Class="WpfApplication1.orderdetail" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="250" Width="450">

<Window.Resources>
    <HierarchicalDataTemplate x:Key="NodeTemplate">
        <TextBlock x:Name="text" Text="?" />
        <HierarchicalDataTemplate.ItemsSource>
            <Binding XPath="child::node()" />
        </HierarchicalDataTemplate.ItemsSource>
        <HierarchicalDataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=NodeType}" Value="Text">
                <Setter TargetName="text" Property="Text" Value="{Binding Path=Value}"></Setter>
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=NodeType}" Value="Element">
                <Setter TargetName="text" Property="Text" Value="{Binding Path=Name}"></Setter>
            </DataTrigger>
        </HierarchicalDataTemplate.Triggers>
    </HierarchicalDataTemplate>
    <XmlDataProvider x:Key="xmlDataProvider"></XmlDataProvider>
</Window.Resources>

<Grid >
    <TreeView Name="treeView1"
          Background="AliceBlue"
          ItemsSource="{Binding Source={StaticResource xmlDataProvider}, XPath=*}"
          ItemTemplate= "{StaticResource NodeTemplate}"/>
</Grid>
</Window>

cs file

 public partial class orderdetail : Window
{
    public int OID { get; set; }
    public orderdetail()
    {
        InitializeComponent();
    }

    private void Bindtree(int orderid)
    {
        string xml = "xml content will be here from api method";
        XmlDataProvider dataProvider = this.FindResource("xmlDataProvider") as XmlDataProvider;
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        dataProvider.Document = doc;

    }
}

I don't want to bind treeview with window InitializeComponent event as like below

    public orderdetail()
    {
        InitializeComponent();
        Bindtree(1);
    }

I will pass dynamically value to this page for bind treeview like below

 orderdetail orderdetail = new orderdetail();
 orderdetail.OID = Convert.ToInt32(1);
 orderdetail.Show();

Is there any event/method to bind treeview dynamically?

like image 356
Chhatrapati Sharma Avatar asked Sep 17 '13 06:09

Chhatrapati Sharma


1 Answers

With WPF you should take advantage of MVVM pattern. I've seen a very good tutorial on using TreeView with MVVM: http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

like image 88
Pavel Murygin Avatar answered Oct 30 '22 21:10

Pavel Murygin