展开全部
首先呢得写个存储数据的类
public class LeafNode
{
private string data;
public string Data
{
get { return data; }
set { data = value; }
}
private List<LeafNode> children;
public List<LeafNode> Children
{
get { return children; }
set { children = value; }
}
}
前台代码:
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:LeafNode}" ItemsSource="{Binding Path=Children}">
<Button Content="{Binding Path=Data}" ToolTip="{Binding Path=Data}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView x:Name="twLeaf" TreeViewItem.Selected="twLeaf_Selected"/>
</Grid>
后台代码://绑定数据和功能实现
List<LeafNode> roots = new List<LeafNode>();
public test3()
{
InitializeComponent();
for (int i = 0; i < 5; i++)
{
LeafNode child = new LeafNode() { Data = "root" + i.ToString() };
child.Children = new List<LeafNode>();
roots.Add(child);
for (int j = 0; j < 10; j++)
{
LeafNode subchild = new LeafNode() { Data = "son" + j.ToString() };
subchild.Children = new List<LeafNode>();
child.Children.Add(subchild);
for (int k = 0; k < 15; k++)
{
LeafNode gs = new LeafNode() { Data = "grantSon" + k.ToString() };
subchild.Children.Add(gs);
}
}
}
twLeaf.ItemsSource = roots;
}
private void twLeaf_Selected(object sender, RoutedEventArgs e)
{
// 点击叶子节点时,希望展开子节点
TreeViewItem item = e.OriginalSource as TreeViewItem;
item.IsExpanded = true;
}
public class LeafNode
{
private string data;
public string Data
{
get { return data; }
set { data = value; }
}
private List<LeafNode> children;
public List<LeafNode> Children
{
get { return children; }
set { children = value; }
}
}
前台代码:
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:LeafNode}" ItemsSource="{Binding Path=Children}">
<Button Content="{Binding Path=Data}" ToolTip="{Binding Path=Data}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView x:Name="twLeaf" TreeViewItem.Selected="twLeaf_Selected"/>
</Grid>
后台代码://绑定数据和功能实现
List<LeafNode> roots = new List<LeafNode>();
public test3()
{
InitializeComponent();
for (int i = 0; i < 5; i++)
{
LeafNode child = new LeafNode() { Data = "root" + i.ToString() };
child.Children = new List<LeafNode>();
roots.Add(child);
for (int j = 0; j < 10; j++)
{
LeafNode subchild = new LeafNode() { Data = "son" + j.ToString() };
subchild.Children = new List<LeafNode>();
child.Children.Add(subchild);
for (int k = 0; k < 15; k++)
{
LeafNode gs = new LeafNode() { Data = "grantSon" + k.ToString() };
subchild.Children.Add(gs);
}
}
}
twLeaf.ItemsSource = roots;
}
private void twLeaf_Selected(object sender, RoutedEventArgs e)
{
// 点击叶子节点时,希望展开子节点
TreeViewItem item = e.OriginalSource as TreeViewItem;
item.IsExpanded = true;
}
更多追问追答
追问
这种方法之前试过啦,拿到的是节点上绑定的数据类,而不是TreeViewItem,所以不能设置IsExpanded属性。况且我当时用到的按钮时SurfaceButton,当时用这种事件的时候Selected事件根本就不能读到。最后解决的方案是在TreeView资源中添加TreeViewItem的Tempater,在模板中定义事件,之后可以在事件中向上查找可以找到当前点击的TreeViewItem。
追答
哦,这样子也行啦,其实也可以写依赖属性去做的。。。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询