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?
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
good template <Grid> <TreeView x:Name="treeView" HorizontalAlignment="Left" Height="227" Margin="10,32,0,0" VerticalAlignment="Top" Width="178" /> </Grid>
and C #
static TreeViewItem item;
static public void Show(TreeView tree)
{
DataSet dsSet = Class.GetDS();
for (int i = 0; dsSet.Tables[0].Rows.Count > i; i++)
{
item = new TreeViewItem();
item.Header = dsSet.Tables[0].Rows[i][1];
for (int j = 0; j < 2; j++)
{
item.Items.Add("Monitor");
item.Items.Add("LapTop");
}
tree.Items.Add(item);
}
}
Show(treeView);
Class.GetDS(); is a static method I took from another class, you can add any additional DataSet.
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.