xaml上的Treeview代码
<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文件
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;
}
}
我不想将treeview与窗口InitializeComponent事件绑定,如下所示
public orderdetail()
{
InitializeComponent();
Bindtree(1);
}
我会动态地将值传递给此页面以获取绑定树视图,如下所示
orderdetail orderdetail = new orderdetail();
orderdetail.OID = Convert.ToInt32(1);
orderdetail.Show();
是否有动态绑定树视图的事件/方法?
答案 0 :(得分:7)
使用WPF,您应该利用MVVM模式。我已经看到了一个关于将TreeView
与MVVM一起使用的非常好的教程:http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode
答案 1 :(得分:0)
好的模板
<Grid>
<TreeView x:Name="treeView" HorizontalAlignment="Left" Height="227" Margin="10,32,0,0" VerticalAlignment="Top" Width="178" />
</Grid>
和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();是我从另一个类中获取的静态方法,您可以添加任何其他DataSet。