是否可以在WPF TreeView中显示(自定义)详细信息?
我想显示计算机的所有服务,并在其旁边显示“描述”,“状态”等,并能够在扩展时订购它。有可能实现吗?
我正在以编程方式创建树,这是我到目前为止所拥有的:
public void LoadServices(object sender, RoutedEventArgs e)
{
TreeView.Items.Clear();
List<string> computers = new List<string> { Environment.MachineName, Environment.MachineName };
foreach (string computer in computers)
{
TreeViewItem CurrComputer = new TreeViewItem { Header = computer };
TreeView.Items.Add(CurrComputer);
Services = ServiceController.GetServices();
foreach (ServiceController tempService in Services)
{
TreeViewItem newService = new TreeViewItem
{
Header = tempService.DisplayName
};
CurrComputer.Items.Add(newService);
}
}
}
/ edit:我能想到的一种解决方案是在其旁边放置一个列表视图,并将其从树视图映射到列表视图。但这并不是很顺利,也意味着如果我按某种顺序排序,则树形视图将不会被排序。
答案 0 :(得分:2)
这是我正在使用的解决方案:建议您使用ObservableCollection编写最少的编码
<Window x:Class="zzWpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:zzWpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Margin="10">
<TreeView Name="trvMenu">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type MenuItem}" ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Title}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ServiceProcess;
using System.Windows;
namespace zzWpfApp2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<string> computers = new List<string> { Environment.MachineName, Environment.MachineName };
MenuItem root = new MenuItem() { Title = "General Menu" };
foreach (string computer in computers)
{
MenuItem childItem = new MenuItem() { Title = computer };
foreach (ServiceController tempService in ServiceController.GetServices())
{
childItem.Items.Add(new MenuItem() { Title = tempService.DisplayName });
}
root.Items.Add(childItem);
}
trvMenu.Items.Add(root);
}
public class MenuItem
{
public MenuItem()
{
this.Items = new ObservableCollection<MenuItem>();
}
public string Title { get; set; }
public ObservableCollection<MenuItem> Items { get; set; }
}
}
}
和结果:
如果您想了解更多信息,请修改循环:
foreach (ServiceController tempService in ServiceController.GetServices())
{
MenuItem subchildItem = new MenuItem() {Title = tempService.DisplayName };
childItem.Items.Add(subchildItem);
subchildItem.Items.Add(new MenuItem() { Title = tempService.Status.ToString()});
subchildItem.Items.Add(new MenuItem() { Title = tempService.ServiceName});
}