1、前台直接写死数据
效果:
代码:
<TreeView x:Name="treeView" HorizontalAlignment="Left" Height="436" Margin="850,65,0,0" VerticalAlignment="Top" Width="179">
<TreeViewItem Header="系统设置" >
<TreeViewItem Header="个人信息设置" Selected="userInfoSet"/>
<TreeViewItem Header="密码管理" Selected="passwordSet"/>
<TreeViewItem Header="意见反馈" />
</TreeViewItem>
<TreeViewItem Header="店铺管理" >
<TreeViewItem Header="店员管理"/>
<TreeViewItem Header="商品管理"/>
</TreeViewItem>
</TreeView>
其中Selected="userInfoSet"是点击节点时触发的事件。
后台事件代码:
public void userInfoSet(object sender, RoutedEventArgs routedEventArgs)
{
MessageBox.Show("个人信息设置");
}
点击效果:
2、从后台加载数据
效果:
前端代码:
<TreeView x:Name="tvProperty" HorizontalAlignment="Left" Height="195" Margin="996,65,0,0" VerticalAlignment="Top" Width="145">
<!--设置treeview背景-->
<TreeView.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFF05F5F" Offset="0"/>
<GradientStop Color="#FFF0A3A3" Offset="1"/>
</LinearGradientBrush>
</TreeView.Background>
<!--加载treeview数据-->
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type myWpfApp:propertyNodeItem}" ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="{Binding DisplayName}" Foreground="White" FontSize="14"/>
<StackPanel.ToolTip>
<TextBlock VerticalAlignment="Center" Text="{Binding Name}" TextWrapping="Wrap" MaxWidth="200px" FontSize="14"/>
</StackPanel.ToolTip>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
注意:DataType="{x:Type myWpfApp:propertyNodeItem}"中myWpfApp为当前命名空间,propertyNodeItem为装载数据的类名。
不要忘了在xml中声明:
xmlns:myWpfApp="clr-namespace:MyWpfApp"
后台代码:
创建一个propertyNodeItem类
//建一个PropertyNodeItem类
public class propertyNodeItem
{
public string Icon { get; set; }
public string DisplayName { get; set; }
public string Name { get; set; }
public List<propertyNodeItem> Children { get; set; }
public propertyNodeItem()
{
Children = new List<propertyNodeItem>();
}
}
在xaml.cs文件中添加方法并在主函数里调用:
public MainWindow()
{
InitializeComponent();
//加载tree数据
ShowTreeView();
}
/// <summary>
/// 加载tree数据
/// </summary>
private void ShowTreeView()
{
List<propertyNodeItem> listItem = new List<propertyNodeItem>();
propertyNodeItem mainNode = new propertyNodeItem()
{
DisplayName = "功能菜单",
Name = "主目录--功能菜单"
};
propertyNodeItem systemNode = new propertyNodeItem()
{
DisplayName = "系统设置",
Name = "当前菜单--系统设置"
};
propertyNodeItem pwdTag = new propertyNodeItem()
{
DisplayName = "密码修改",
Name = "当前选项--密码修改"
};
systemNode.Children.Add(pwdTag);
mainNode.Children.Add(systemNode);
listItem.Add(mainNode);
this.tvProperty.ItemsSource = listItem;
}